【问题标题】:Exiting loop with numeric input from user使用来自用户的数字输入退出循环
【发布时间】:2015-05-20 20:31:06
【问题描述】:

我可以问一下这个问题有什么建议的解决方案吗?当用户输入-1时,这将被计入总数,这不是我们想要的。我试图在不使用 if 控制结构的情况下做到这一点。

    int numberToAdd = 0, total = 0;
    Scanner input = new Scanner(System.in);

    while (numberToAdd != -1) {
        System.out.println("Number to add? -1 to quit");
        numberToAdd = input.nextInt();
        total = total + numberToAdd;
    }
    System.out.println("Total: = " + total);

我知道我可以改为使用字符串并使用作为字符串的退出代码,同时将字符串输入解析为整数,但是我正在尝试使用整数(在本例中为 -1)来完成此操作。

谢谢

【问题讨论】:

    标签: java loops input exit


    【解决方案1】:

    如果你在循环之前读取第一个输入,你可以在没有 if 语句的情况下实现你想要的:

    System.out.println("Number to add? -1 to quit");
    numberToAdd = input.nextInt();
    while (numberToAdd != -1) {
        total = total + numberToAdd;
        System.out.println("Number to add? -1 to quit");
        numberToAdd = input.nextInt();
    }
    

    这是一种使代码更短的方法:

    System.out.println("Number to add? -1 to quit");
    while ((numberToAdd = input.nextInt()) != -1) {
        total = total + numberToAdd;
        System.out.println("Number to add? -1 to quit");
    }
    

    【讨论】:

    • 这(在循环之前立即读取输入)是否适用于所有需要用户输入的哨兵控制循环?
    • @151SoBad 我不知道你所说的“所有哨兵控制的循环”是什么意思
    • 对不起,我指的是 while() 循环
    【解决方案2】:

    你也可以使用do...while循环来解决你的问题。

        int numberToAdd = 0, total = 0;
        Scanner input = new Scanner(System.in);
        System.out.println("Number to add? -1 to quit");
    
       do{
             total = total + numberToAdd;
             System.out.println("Number to add? -1 to quit");
             numberToAdd = input.nextInt();
         }while(numberToAdd != -1) 
    

    【讨论】:

      【解决方案3】:

      使用do-while循环:

      int numberToAdd = 0, total = 0;
      Scanner input = new Scanner(System.in);
      
      do {
          total += numberToAdd;
          System.out.println("Number to add? -1 to quit");            
          numberToAdd = input.nextInt();
      } while (numberToAdd != -1);
      
      System.out.println("Total: = " + total);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-08-24
        • 2021-11-13
        • 1970-01-01
        • 1970-01-01
        • 2018-07-25
        • 2014-04-12
        • 1970-01-01
        相关资源
        最近更新 更多