【问题标题】:Do while loop displaying contents 3 times in cmd在cmd中执行while循环显示内容3次
【发布时间】:2016-12-13 14:48:43
【问题描述】:

我有以下程序,在运行它时,我打印了 3 次菜单。我只期待一个并立即提示输入。

class whileexample2
{
    public static void main(String args[]) throws java.io.IOException
    {
        char i;
        int a = 100;
        int b = 20;
        do
        {
            System.out.println("select your choice");
            System.out.println("---------------------");
            System.out.println("(1) Additon");
            System.out.println("(2) Subtraction");
            System.out.println("(3) Multiplication");
            System.out.println("(4) Division");
            i = (char) System.in.read();
        } while (i < '1' || i > '4');
        System.out.println("\n");
        switch(i)
        {
            case '1':
            {
                System.out.println("Result of addition is: " + (a + b));
                break;
            }
            case '2':
            {
                System.out.println("Result of subtraction is: " + (a - b));
                break;
            }
            case '3':
            {
                System.out.println("Result of multiplication is: " + (a * b));
                break;
            }
            case '4':
            {
                System.out.println("Result of division is: " + (a / b));
                break;
            }
        }
    }
}

输出

选择您的选择
---------------------
(1) 附加
(2) 减法
(3) 乘法
(4) 师
7    //输入错误,因此再次显示菜单,但会打印3次 选择您的选择
---------------------
(1) 附加
(2) 减法
(3) 乘法
(4) 师
选择您的选择
---------------------
(1) 附加
(2) 减法
(3) 乘法
(4) 师
选择您的选择
---------------------
(1) 附加
(2) 减法
(3) 乘法
(4) 师
2

减法结果为:80

【问题讨论】:

  • 是不是因为你在 do...while 循环中打印了菜单?
  • @BretC:我想在输入无效输入时重复菜单,因此我在 do..while 循环中打印它。但不知道为什么它在无效输入输入时显示 3 次。输入正确的输入时,它可以正常工作。

标签: java


【解决方案1】:
i = (char) System.in.read();

这条线给你带来了问题。您在此流中输入的不仅仅是一个数字,因为当您点击“Enter”时,您将在流中插入一个回车符,然后是一个换行符。这会导致您的 while 循环经过 3 次,因为它正在读取的流包含字符“7”、“\r”和“\n”。

考虑改用扫描仪并仅检查输入的第一个字符。扫描仪往往更可靠且独立于平台:

import java.util.Scanner;

class WhileExample2{
    public static void main(String args[]){
        Scanner kb = new Scanner(System.in);
        char i;
        int a=100;
        int b=20;
        do
        {
            System.out.println("select your choice");
            System.out.println("---------------------");
            System.out.println("(1) Additon");
            System.out.println("(2) Subtraction");
            System.out.println("(3) Multiplication");
            System.out.println("(4) Division");
            i = kb.nextLine().charAt(0);
        }while(i < '1' || i > '4');
        //rest of code
    }
}

【讨论】:

  • 我建议kb.nextLine() 阅读所有内容,直到返回。 (此外,您在示例中声明了两次扫描仪。)
【解决方案2】:

switch 语句应该在 Do-While 循环中

【讨论】:

    猜你喜欢
    • 2021-06-30
    • 1970-01-01
    • 2019-09-03
    • 2016-01-22
    • 2014-01-21
    • 2023-04-02
    • 2013-08-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多