嵌套在while循环中

时间:2016-09-28 18:27:01

标签: java if-statement while-loop nested-if

在执行时我的while循环重复时遇到了一些问题。 if语句按预期工作,但从扫描程序返回的char值没有进入我的while循环。有人知道我做错了什么或更好的解决方案吗?

package classWork;
import java.util.Scanner;

public class project_2 {
    public static void main(String[] args){

        Scanner input = new Scanner(System.in);
        int choice = 0;
        double celsius, fahrenheit, inches, centimeters;
        char doAgain = 'y';

        while (doAgain == 'y' || doAgain == 'Y')
        {

        System.out.print(" Main Menu \n 1. Celsius to Fahrenheit \n 2. Inches to Centimeters \n"
                + "Please select either 1 or 2 \nThen press enter to continue");
        choice = input.nextInt();

        if (choice == 1)
        {
            System.out.println("This program will convert a celsius value into a fahrenheit one. \n");

            System.out.println("Please enter the tempature for conversion: ");
            celsius = input.nextInt();

            fahrenheit = 1.8 * celsius + 32.0;

            System.out.println(celsius + " degree(s) in celcius" + " is " + fahrenheit + 
                    " in fahrenheit. \n");

            System.out.println("Do you want to continue?\n: " +
                       "enter a \'y \' for another round\n " +
                      " enter a\'n\'   to end the program\n");

            doAgain = input.next().charAt(0);

            input.close();
            return;
        }

        if (choice == 2)
        {
            System.out.println("This program will convert inches to centimeters. \n");


            System.out.println("Please enter the length for conversion: ");
            inches = input.nextInt();

            centimeters = 2.54 * inches;

            System.out.println(inches + " inches is " + centimeters + " centimeters. \n");

            System.out.println("Do you want to continue?\n: " +
                       "enter a \'y \' for another round\n " +
                      " enter a\'n\'   to end the program\n");

            doAgain = input.next().charAt(0);

            input.close();
            return;
        }

        else
        {
            System.out.println("That is not a valid option. Please restart and try again");
            input.close();
            }
        }
    }
}

2 个答案:

答案 0 :(得分:1)

您需要删除返回,它完成主线程的执行

答案 1 :(得分:1)

您的计划实际上有3个问题

1。不要调用return继续迭代

在2个if数据块的末尾,您调用return,这会使您的应用程序退出main方法,因此退出您的应用程序,这实际上是您当前的问题。

只需删除它们或使用continue代替。

2。请勿致电close继续阅读

在2 if个阻止结束时,您拨打input.close()关闭扫描程序,这样您就无法在没有IllegalStateException的情况下阅读任何内容。

所以简单地删除它们。

3。第二个if应为else if

你的代码应该是:

if (choice == 1)
{
    ...
}
else if (choice == 2)
{
    ...
}
else
{
    ...
}

如果你的第一个选择是1,那么你键入y来迭代你的应用程序将会进入else以后的choice != 2 close扫描仪,因为它被错误地视为无效选项。