循环验证用户输入

5

我对Java编程还不够熟练,现在想写一个小程序,让用户输入3个1到10之间的整数,将它们保存在一个数组中,然后把这些整数加起来并告诉用户结果。目前为止,我已经写好了下面这段代码,并且它可以正常运行:

import java.util.Scanner;

public class Feb11a {

    public static void main(String[] args) {

        int[] numArr = new int[3];
        int sum = 0;
        Scanner keyboard = new Scanner(System.in);
        System.out.println("Enter 3 numbers in the range 1 to 10: ");

        for (int i = 0; i < numArr.length; i++) {
            numArr[i] = keyboard.nextInt();
        }

        for (int counter = 0; counter < numArr.length; counter++) {
            sum += numArr[counter];
        }

        System.out.println("The sum of these numbers is " + sum);
    }
}

我的问题是,我还需要验证输入的内容,例如,如果他们输入一个双精度数、一个字符串或者在1-10范围之外的数字。我尝试使用while循环,但我无法让程序正常工作,以下是我目前的代码。如果我去掉第一个while循环,第二个就能正常工作,也就是检查它是否为整数:

import java.util.Scanner;

public class Feb11a {

    public static void main(String[] args) {

        int[] numArr = new int[3];
        int sum = 0;
        Scanner keyboard = new Scanner(System.in);

        for (int i = 0; i < numArr.length; i++) {
            //check if between 1 and 10
            while (i > 10 || i < 1) {
                System.out.println("Enter a number in the range 1 to 10: ");

                //check if integer      
                while (!keyboard.hasNextInt()) {
                    System.out.println("Invalid entry, please try again ");
                    keyboard.next();
                }
                numArr[i] = keyboard.nextInt();
            }
        }

        for (int counter = 0; counter < numArr.length; counter++) {
            sum += numArr[counter];
        }

        System.out.println("The sum of these numbers is " + sum);
    }
}

我的问题是如何检查它是否是整数,且在1-10的范围内?


1
你的for循环会循环数组中的项数次。然而,你没有检查数组的值。你检查了迭代i(while (i>10 || i<1))。你需要遍历整个数组。 - ltalhouarne
4个回答

3
import java.util.Scanner;

public class NewClass {

public static void main(String[] args) 
{

int[] numArr = new int[3];
int sum=0,x;
Scanner keyboard = new Scanner(System.in);



  for(int i=0; i<numArr.length; i++)
 {
        //check if between 1 and 10
     System.out.println("Enter a number in the range 1 to 10: ");

                //check if integer      
    while (!keyboard.hasNextInt())
    {
        System.out.println("Invalid entry, please try again ");
        keyboard.next();
    }
            x = keyboard.nextInt();
           if(x>0 && x<=10)
             numArr[i]=x;
           else{
               System.out.println("Retry Enter a number in the range 1 to 10:");
               i--;
           }

}


     for (int counter=0; counter<numArr.length; counter++)
    {
        sum+=numArr[counter];
    }
    System.out.println("The sum of these numbers is "+sum);
 }

}

1
@user127378请考虑将其标记为答案,如果您找到一个好的答案,到达可以这样做的时候请点赞。 - Maythux
1
好的,我该如何标记为答案?顺便说一下,我刚刚编辑了我的名字,我想明白了。谢谢。 - Mary Kelly

1

要检查简单使用Integer.parseInt()并捕获NumberFormatException(与Scanner.next()一起)。

一旦格式正确,您可以进行int比较(i>0 && i<11)


如果他们输入11会怎么样? - Ben Thurley
我对Java还很陌生,还没有接触过Integer.parseInt()。它是用来做什么的? - Mary Kelly

0

我建议您使用org.apache.commons.lang.math下的NumberUtils

它有一个isDigits方法,用于检查给定字符串是否仅包含数字:

if (NumberUtils.isDigits(str) && NumberUtils.toInt(str) < 10) {
    // your requirement
}

请注意,toInt对于大数值会返回零!
也许仅出于这个原因,添加整个库似乎是不必要的,但对于更大的项目,您将需要像Apache CommonsGuava这样的库。

0

你可以将System包装在BufferedReader中,以读取用户输入的任何内容,然后检查它是否为“int”,并重复要求用户输入。

我稍微修改了你的代码,使其能够工作。

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class Feb11a {

    public static void main(String[] args) throws NumberFormatException, IOException
    // You may want to handle the Exceptions when calling the getInt function
    {
        Feb11a tester = new Feb11a();
        tester.perform();
    }

    public void perform() throws NumberFormatException, IOException
    {
        int[] numArr = new int[3];
        int sum = 0;
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

        for (int i = 0; i < numArr.length; i++) 
        {
            int anInteger = -1;
            do
            {
                // First get input from user.
                System.out.println("Enter a number in the range 1 to 10: ");
                anInteger = getInt(in);
            } while (anInteger > 10 || anInteger < 1);  // then check for repeat condition. Not between 1 and 10.

            numArr[i] = anInteger;  // set the number into the array.
        }


        for (int counter = 0; counter < numArr.length; counter++) 
        {
            sum += numArr[counter];
        }
        System.out.println("The sum of these numbers is " + sum);
    }

    public int getInt(BufferedReader br) throws NumberFormatException, IOException
    {
        String str = br.readLine();
        int toReturn = Integer.parseInt(str);
        return toReturn;
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接