gpt4 book ai didi

java - if...elseif 一次又一次输入值时出错

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:45:58 29 4
gpt4 key购买 nike

虽然在这个程序中,我必须在一个循环中一次又一次地输入温度。当我输入温度后显示正确时,但是当我再次输入温度时程序自行终止。

代码是:

import java.util.Scanner;

public class CheckTemperature
{
public static void main(String [] args)
{
final double TEMPERATURE = 102.5;
double thermostat;

Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the substance's temperature: ");
thermostat = keyboard.nextDouble();

if(thermostat > TEMPERATURE)
{
System.out.print("The temperature is too high. ");
System.out.print("Turn down the thermostat. ");
System.out.println("Wait for 5 minutes and check the thermostat again. ");
System.out.println("Enter the thermostat here: ");
thermostat = keyboard.nextDouble();
}
else if(thermostat < TEMPERATURE)
{
System.out.println("The temperature is low.");
System.out.println("Turn up the thermostat.");
System.out.println("Check for 5 minutes and check again.");
System.out.println("Enter the thermostat here: ");
thermostat = keyboard.nextDouble();
}
else if(thermostat == TEMPERATURE)
{
System.out.println("The temperature is acceptable. Check again in 15 minutes.");
System.out.println("Enter the thermostat here: ");
thermostat = keyboard.nextDouble();
}
else
{
System.out.println("Enter the correct temperature value ");
System.out.println("Enter the thermostat here: ");
thermostat = keyboard.nextDouble();
}
}
}

最佳答案

这是因为您不在循环中。你在顶部问一次温度。然后偶尔一次,然后就结束了。

public static void main(String [] args) 
{
final double TEMPERATURE = 102.5;
double thermostat;
Scanner keyboard = new Scanner(System.in);

while (true) {
System.out.println("Enter the substance's temperature: ");
thermostat = keyboard.nextDouble();

if(thermostat > TEMPERATURE)
{
System.out.print("The temperature is too high. ");
System.out.print("Turn down the thermostat. ");
System.out.println("Wait for 5 minutes and check the thermostat again. ");
}
else if(thermostat < TEMPERATURE)
{
System.out.println("The temperature is low.");
System.out.println("Turn up the thermostat.");
System.out.println("Check for 5 minutes and check again.");
}

else if(thermostat == TEMPERATURE) {

System.out.println("The temperature is acceptable. Check again in 15 minutes.");
}

else{
System.out.println("Enter the correct temperature value ");
}
}
}

小心,while 永远不会停止,但您可以根据需要更改条件。

关于java - if...elseif 一次又一次输入值时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31638860/

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