无论如何,代码都会再次运行。

时间:2016-02-21 02:02:59

标签: java bluej

我不知道为什么,但是下面的代码会让用户再次运行代码,无论他们选择与否。我尝试了很多东西,但它无法正常工作。

谢谢!

 public static void main (String [ ] args)
{


    boolean a = true;
    while (a)
    {
        Scanner scan = new Scanner(System.in);

        System.out.print("Enter an integer:  ");
        int x = scan.nextInt();



        System.out.print("\n\nEnter a second integer:  ");
        int z = scan.nextInt();

        System.out.println();
        System.out.println();

        binaryConvert1(x, z);



        System.out.println("\n\nWould you like to run this code again? Enter \"Y\" or \"N\".");
        System.out.print("Enter your response here:  ");

        String RUN = scan.nextLine();
        String run = RUN.toLowerCase();
        if (run.equals("n"))
        {
            a = false;
        }

        System.out.println();
        System.out.println();
    }
    System.out.println("Goodbye.");
}

1 个答案:

答案 0 :(得分:0)

Scanner.nextInt()不会消耗缓冲区中的行结束字符,这就是为什么当您使用scan.nextLine()读取“是/否”问题的值时,您将收到一个空字符串而不是用户输入的值。

解决此问题的一种简单方法是使用Integer.parseInt()显式解析原始行中的整数:

System.out.print("Enter an integer:  ");
int x = Integer.parseInt(scan.nextLine());

System.out.print("\n\nEnter a second integer:  ");
int z = Integer.parseInt(scan.nextLine());
相关问题