当我运行该程序时,它运行 else 部分并执行但是在 if 部分它只是保持循环并且不会停止,直到我必须强制停止它。我试图在选择上从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();
}
}
}
答案 0 :(得分:3)
这是一个无限循环。你也可以写while (true)
尝试while (meters <= 0)
或while (meters >0)
或者:
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();
}
您的输出也指定“大于1”,因此您的条件需要同意。
答案 1 :(得分:1)
while (meters <=0 || meters > 0) is an infinite loop
答案 2 :(得分:0)
循环中指定的条件是矛盾的。必须使用这样的条件:
while (meters >= 0)
{
// logical statements here if the condition is satisfied
}
else
{
// logical statements here if the condition is not satisfied
}