gpt4 book ai didi

java - 检查温度条件

转载 作者:行者123 更新时间:2023-12-02 10:15:24 27 4
gpt4 key购买 nike

如何在这三个条件下设置合适的温度,至少在 98°C、99°C、1°C 和 2°C 等?

package boiling.freezing;

import java.util.Scanner;

public class BoilingFreezing {

public static void main(String[] args) {
System.out.println("Give the temperature : ");
Scanner sc = new Scanner(System.in);
int temp = sc.nextInt();
if (temp >= 100){
System.out.println("The water is boiling!");
}
else if (temp <= 0){
System.out.println("The water is freezing!");
}
else{
System.out.println("The water is at normal_state!");
}
}
}

最佳答案

我将向您提供一个模式,而不是一个简单的if-elseif-else block 。

您可能想要一个接口(interface)温度

interface Temperature {
/** Returns true if the temperature matches the criteria. */
boolean within(final int temperature);

/** Returns an appropriate, descriptive, message. */
String message();
}

然后您可以实现此接口(interface)来满足您的多个条件

class BoilingTemperature implements Temperature {
public boolean within(final int temperature) {
return temperature > 99;
}

public String message() {
return "Water boiling";
}
}

class FreezingTemperature implements Temperature {
public boolean within(final int temperature) {
return temperature < 1; // Should be 3 degree! But anyway.
}

public String message() {
return "Water freezing";
}
}

您可以使用此模式编写自定义温度处理程序

class YourCustomTemperature implements Temperature {
public boolean within(final int temperature) {
return temperature > 6 && temperature < 40;
}

public String message() {
return "Your custom message";
}
}

您需要维护这些具体实现的列表并循环它们以检查哪些匹配。

final List<Temperature> temperatures = new ArrayList<>(6);
temperatures.add(new BoilingTemperature());
temperatures.add(new FreezingTemperature());
temperatures.add(new YourCustomTemperature());
...

然后

public static void main(String[] args) {
System.out.println("Give the temperature : ");
final Scanner sc = new Scanner(System.in);
int temp = sc.nextInt();

for (final Temperature t : temperatures) {
if (t.within(temp)) {
System.out.println(t.message());
}
}
}

关于java - 检查温度条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54721323/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com