循环中的数据验证输入

时间:2012-02-12 17:50:48

标签: java

我尝试过各种技术来检查此方法中的用户输入值。用户应该只能输入“1”或“0”。如果使用任何其他输入,则应该出现错误消息并退出程序。有任何想法吗?我把它用于第一个数字但不是第二个到第十个数字。

    System.out.println("Enter a ten digit binary number.  Press 'Enter' after each digit.  Only use one or zero. :");

        binary[0] = keyboard.nextInt();

        for (index = 1; index < 10; index++)
            binary[index] = keyboard.nextInt();// fill array with 10 binary
                                                // digits from user. User
                                                // must press 'Enter' after
                                                // each digit.

2 个答案:

答案 0 :(得分:2)

试试这个:

    Scanner scanner = new Scanner(System.in);
    if (scanner.hasNext())
    {
        final String input = scanner.next();
        try
        {
            int num = Integer.parseInt(input, 2);
        }
        catch (NumberFormatException error)
        {
            System.out.println(input + " is not a binary number.");
            //OR You may exit here, if you don't want to continue
        }
    }

答案 1 :(得分:1)

试试这段代码:

import java.util.Scanner;

public class InputTest
{
    public static void main(String... args) throws Exception
    {
        Scanner scan = new Scanner(System.in);

        int[] binary = new int[10];
        for (int index = 0; index < 10; index++)
        {
            int number = scan.nextInt();
            if (number == 0 || number == 1)
            {
                binary[index] = number;
                System.out.println("Index : " + index);
            }
            else
                System.exit(0);
        }
    }
}