循环以验证用户输入

时间:2014-02-11 14:10:18

标签: java loops

我是Java的新手,我正在尝试编写一个小程序,要求用户在1-10之间输入3个整数,将它们存储在一个数组中,然后将整数相加并告诉用户答案。到目前为止,我已经写了这个并且它有效:

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);
    }
}

我的问题是我也打算验证输入,如果他们输入一个double,一个字符串或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范围?

4 个答案:

答案 0 :(得分: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 :(得分:1)

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

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

答案 2 :(得分:0)

我建议您在NumberUtils

下使用org.apache.commons.lang.math

它有isDigits方法来检查给定的字符串是否只包含数字:

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

请注意,toInt为大数字返回零!

也许因为这个原因添加一个完整的库似乎是不必要的,但对于更大的项目,你需要像Apache CommonsGuava这样的库

答案 3 :(得分:0)

您可以将系统包装到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;
    }
}