扫描仪输入循环直到输入或按键

时间:2021-03-19 16:00:02

标签: java eclipse input java.util.scanner

我正在创建一个 java 程序,要求用户提供 2 个输入,第一个输入将是分子,第二个输入将是分母。例如,如果我写 10 5(用户按 Enter),那么答案将是 2,因为 10/5 = 2。

我还希望能够写几个输入,例如:10 5 20 4 30 5(用户按回车键) 那么答案将是 2、5、6。 如果我写 10 5 20(用户按回车键) 那么答案只有 2,第三个输入被忽略。

这是我的代码:


public class test {

   private static Scanner userpress = new Scanner(System.in);

   public static void main(String[] args) {
      int choice = 1;
      int r;
      int h;

      System.out.println("---------------------------------");
      System.out.println("write your two numbers (numerator, denominator)");

      while (userpress.hasNextInt()) {
         userpress.useDelimiter("\\s");
         r = userpress.nextInt();
         h = userpress.nextInt();
         userpress.nextLine();
         int x = r / h;
         System.out.println(x);
      }
        System.out.println("user dont want play more!")

   }

}

当我写 10 5 20 5 我得到输出 2。但我想得到输出 2、4。如果我写 10 5 20 5 30 6,我想得到输出 2、4、5。我该怎么做?如果用户写了10 5 20 5 e,那么我希望输出是2、4,用户不想再玩了!

1 个答案:

答案 0 :(得分:0)

循序渐进:

    1. 只需在 while 循环之前获取分隔符即可。
    1. 删除 nextLine()。
    1. 如果您需要其他改进,请告诉我们(例如退出程序)。
        userpress.useDelimiter("\\s"); // here
        while (userpress.hasNextInt()) {
            // userpress.useDelimiter("\\s"); // remove
            if(userpress.hasNextInt()) // for uneven values
                r = userpress.nextInt();
            if(userpress.hasNextInt()) // for uneven values
                h = userpress.nextInt();
            //userpress.nextLine(); // remove 
            int x = r / h;
            System.out.println(x);

            // for "e" 
            if( !userpress.hasNextInt() && userpress.hasNextLine()) { // if input is not integer and exists
                message();
                /*String e =*/ userpress.nextLine(); // clean the cache
            }
        }