【问题标题】:Java Scanner input validation causing loop to end earlyJava Scanner 输入验证导致循环提前结束
【发布时间】:2021-04-20 05:56:41
【问题描述】:

我正在用 for 循环填充一个 Double 数组,循环运行用户在第 4 行输入的圈数。但是,正如我在图片中展示的那样:

我进入 3 圈,问题提示 3 次,但是我的数据验证吃掉了我正在寻找的输入之一。

我该如何解决这个问题?我觉得它很简单。

import java.util.Scanner;
public class JK_FINALPRAC1 {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Time-Trial Statistics Program\n");
        System.out.println("This program will ask you to input split-times for each lap or length of a race. The ");
        System.out.println("program will then calculate some basic statistics from the split-times.\n");

        System.out.print("Enter the number of laps or lengths in the race: ");
        int arraySize = sc.nextInt();
        Double[] lapArray = new Double[arraySize];
        System.out.println("Now input the elapsed time (split time) in seconds for each lap/length of the race.");
        int index = 1;
        double currentNum = 0.0;
        for(int i=0;i<arraySize;i++){
            System.out.print("Time for lap or length #" + index + ": ");
            currentNum = sc.nextDouble();
            if(currentNum > 0 && currentNum < 61){
            lapArray[i] = currentNum;
            index++;
            }else if(currentNum<0 || currentNum >60){
            System.out.println("Invalid input! Time must be between 0 and 60.");
            }
        }

    }

【问题讨论】:

    标签: java validation for-loop java.util.scanner


    【解决方案1】:
            double currentNum = 0.0;
            while (index < arraySize) {
                System.out.print("Time for lap or length #" + (index + 1) + ": ");
                currentNum = sc.nextDouble();
                if (currentNum > 0 && currentNum < 61) {
                    lapArray[index] = currentNum;
                    index++;
                } else if (currentNum < 0 || currentNum > 60) {
                    System.out.println("Invalid input! Time must be between 0 and 60.");
                }
            }
    

    由于您正在运行 for 循环,因此 i 每次都会递增(即使您的验证失败)。

    【讨论】:

      【解决方案2】:

      这很简单:为了确保您在不吃一圈的情况下插入了一个替身,请将您的扫描仪输入行放在一个 while 循环中

       do{
          double x = scanner.nextDouble(); 
       }while(x < 0 || x > 60);
      

      这不会提供for循环递增计数器,除非do-while条件为假。

      为了打印验证,也:

       double x = scanner.nextLine();
       while( x < 0 || x > 60){
            //print message
            //scanner again
       }
      

      【讨论】:

      • 如果验证规则超出范围,我该如何打印(例如无效输入!时间必须在 0 到 60 之间。)?
      • 你的意思是每次双插入错误时都要打印验证规则?然后我建议你使用while循环而不是do-while(这是为了不打印你的验证也是第一个输入)。您只需要输入,稍后检查,如果错误,打印您的验证规则并重新输入。我要编辑我的帖子
      猜你喜欢
      • 2016-02-06
      • 2016-02-08
      • 2014-12-28
      • 1970-01-01
      • 2021-02-25
      • 1970-01-01
      • 1970-01-01
      • 2013-10-21
      • 1970-01-01
      相关资源
      最近更新 更多