【问题标题】:Looping a program with user input in Java在 Java 中使用用户输入循环程序
【发布时间】:2015-10-17 18:20:22
【问题描述】:

我只想在用户输入“yes”的情况下循环这个程序。我想我会在整个程序周围使用do/while 循环,但没有任何反应。这是我的代码:

public static void main(String[] args) {
    int num1, i;
    Scanner Scan = new Scanner(System.in);
    do {
        do {
            System.out.print("Enter a number between 20 and 30 ---> ");
            num1 = Scan.nextInt();
        } while (num1 > 30 || num1 < 20);

        for (i = num1; i >= 20; i--) {
            System.out.print(i + " ");
        }
        System.out.println("");
    } while (Scan.equals("yes"));
}

【问题讨论】:

  • 在向用户显示数字列表后,您并没有要求用户输入YES,因此Scan 仍然包含他输入的数字。

标签: java loops while-loop


【解决方案1】:
public static void main(String[] args) {
    int num1, i;
    String choice;
    Scanner Scan = new Scanner(System.in);

    do {
        do {
            System.out.print("Enter a number between 20 and 30 ---> ");
            num1 = Scan.nextInt();
        } while (num1 > 30 || num1 < 20);

        for (i = num1; i >= 20; i--) {

            System.out.print(i + " ");
        }

        System.out.println("");
        choice = Scan.next();
    }
    while (choice.equals("yes"));
}

您需要阅读用户输入的选择。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-13
    • 1970-01-01
    • 2012-08-30
    • 1970-01-01
    • 2015-06-14
    相关资源
    最近更新 更多