[英]What is wrong with my while loop in this java program?
When I run the program it runs the else part and executes but on the if part it just keeps looping and doesn't stop until I have to forcibly stop it. 当我运行程序时,它将运行else部分并执行,但是在if部分,它将一直循环并且直到我不得不强行停止它后才停止。 I'm trying to give it parameters on the choice from 1 to 4 and parameters to meters that doesn't go under 1. is there an alternative to having the parameters?
我正在尝试为它提供从1到4的选择参数,以及不低于1的仪表参数。是否有替代方法?
import java.util.*;
public class Project4
{
public static void showKilometers(double meters) //this is a parameterized function
{
double kilometers = meters * 0.001;
System.out.println(meters +" meters is " + kilometers + " kilometers.");
}
public static void showInches(double meters)
{
double inches = meters * 39.37;
System.out.println(meters +" meters is " + inches + " inches.");
}
public static void showFeet(double meters)
{
double feet = meters * 3.281;
System.out.println(meters +" meters is " + feet + " feet.");
}
public static void quitProgram()
{
System.out.println("Goodbye!");
System.out.println(0);
}
public static void showMenu()
{
System.out.println(" 1. Convert to kilometers ");
System.out.println(" 2. Convert to inches ");
System.out.println(" 3. Convert to feet ");
System.out.println(" 4. Quit the program ");
System.out.println(" ");
}
public static void main (String [] args)
{
double meters;
int choice;
Scanner keyboard = new Scanner (System.in);
System.out.println("Enter a distance in meters: ");
meters = keyboard.nextDouble();
while (meters <=0 || meters > 0)
{
if (meters > 0)
{
showMenu();
meters = keyboard.nextDouble();
}
else
{
System.out.println("Please enter a number greater than 1");
meters = keyboard.nextDouble();
showMenu();
}
}
choice = keyboard.nextInt();
switch(choice) //note the use of switch case
{
case 1: showKilometers(meters);
break;
case 2:showInches(meters);
break;
case 3:showFeet(meters);
break;
case 4:
quitProgram();
}
}
}
It's an infinite loop. 这是一个无限循环。 You might as well write
while (true)
您最好写
while (true)
Try either while (meters <= 0)
or while (meters >0)
尝试
while (meters <= 0)
或while (meters >0)
Or: 要么:
Scanner keyboard = new Scanner (System.in);
System.out.println("Enter a distance in meters: ");
meters = keyboard.nextDouble();
while (meters < 1 || meters.isNaN())
{
System.out.println("Please enter a number greater than 1");
meters = keyboard.nextDouble();
showMenu();
}
Your output also specifies "Greater than 1", so your condition needs to agree. 您的输出还指定了“大于1”,因此您的条件需要同意。
while (meters <=0 || meters > 0) is an infinite loop
The condition specified in the loop is contradictory. 循环中指定的条件是矛盾的。 The condition must be used like this :
条件必须这样使用:
while (meters >= 0)
{
// logical statements here if the condition is satisfied
}
else
{
// logical statements here if the condition is not satisfied
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.