Mur*_*ora 3 java loops if-statement
在这个程序中,我必须一次又一次地在循环中输入温度.当我输入温度一旦它显示正确的显示,但当我再次输入温度时,程序自行终止.
代码是:
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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是因为你不在循环中.你问温度一次在顶部.然后在if中,然后结束.
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 ");
}
}
}
Run Code Online (Sandbox Code Playgroud)
小心,暂时不会停止,但你可以根据自己的意愿改变条件.