0

当我运行程序时,它运行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();
            }
    }
}
4

3 回答 3

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”,因此您的条件需要同意。

于 2012-11-17T19:33:08.927 回答
1
 while (meters <=0 || meters > 0) is an infinite loop
于 2012-11-17T19:34:25.063 回答
0

循环中指定的条件是矛盾的。条件必须像这样使用:

while (meters >= 0)
{
    // logical statements here if the condition is satisfied
}
else
{
    // logical statements here if the condition is not satisfied
}
于 2013-11-06T09:43:49.243 回答