首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java Scanner输入验证导致循环提前结束

Java Scanner输入验证导致循环提前结束
EN

Stack Overflow用户
提问于 2021-04-20 13:56:42
回答 2查看 49关注 0票数 0

我用一个for循环填充一个双数组,这个循环运行用户在第4行输入的圈数。然而,正如我在我的图片中演示的:

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

我该如何解决这个问题?我觉得这是很简单的事情。

代码语言:javascript
复制
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.");
            }
        }

    }

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-04-20 14:14:18

代码语言:javascript
复制
        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-loop,因此每次都会递增I(即使您的验证失败了)。

票数 1
EN

Stack Overflow用户

发布于 2021-04-20 14:03:21

这很简单:为了确保您插入的是double而不是一圈,请将您的扫描仪输入行放入while循环中

代码语言:javascript
复制
 do{
    double x = scanner.nextDouble(); 
 }while(x < 0 || x > 60);

这将无法提供for循环递增计数器,除非do-while的条件为false。

为了打印验证,还需要:

代码语言:javascript
复制
 double x = scanner.nextLine();
 while( x < 0 || x > 60){
      //print message
      //scanner again
 }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67173247

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档