程序不会在预期的点停止(接收字符串)

时间:2011-10-28 12:56:49

标签: java

import java.util.Scanner;

public class Power1Eng {

    public static void main(String[] args) {

        double x, prod = 1;
        int n;
        String s;

        Scanner input = new Scanner(System.in);

        System.out.print("This program prints x(x is a real number) raised to the power of n(n is an integer).\n");

        outer_loop:
        while (true) {
            System.out.print("Input x and n: ");
            x = input.nextDouble();
            n = input.nextInt();

            for (int i = 1; i <= n; i++) {
                prod *= x;
            }

            System.out.printf("%.1f raised to the power of %d is %.4f. Do you want to continue?(Y/N) ", x, n, prod);
            s = input.nextLine();

            if (s.equals("Y"))
                continue;
            else if (s.equals("N"))
                break;
            else {
                inner_loop:
                while (true) {
                    System.out.print("Wrong input. Do you want to continue?(Y/N) ");
                    s = input.nextLine();

                    if (s.equals("Y"))
                        continue outer_loop;
                    else if (s.equals("N"))
                        break outer_loop;
                    else
                        continue inner_loop;
                }   
            }   
        }       
    }

}

enter image description here

查看控制台。在第三行中,我预计程序会打印到第一个“你想继续吗?(Y / N)”,但它也会输出错误的输入。你想继续吗?(是/否)'。我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

当您执行nextIntnextDouble时,它不会清除该行的(空)其余部分。

您需要在阅读这些值后调用nextLine以清除该行的其余部分。

答案 1 :(得分:0)

System.out.printf("%.1f raised to the power of %d is %.4f. Do you want to continue?(Y/N) \n", x, n, prod);
s = input.next();

这将解决您的问题,也不会使用标签。

Should I avoid using Java Label Statements?

维护该代码的人会找到你。