首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >循环中的数据校验输入

循环中的数据校验输入
EN

Stack Overflow用户
提问于 2012-02-13 01:50:48
回答 2查看 642关注 0票数 2

我尝试了各种技术来检查此方法中用户输入的值。用户应该只能输入“1”或“0”。如果使用了任何其他输入,则应该会出现一条错误消息,程序将退出。有什么想法吗?我让它对第一个数字起作用,但不能从第二个数字到第十个数字。

代码语言:javascript
复制
    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.
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-02-13 02:13:01

试试这个:

代码语言:javascript
复制
    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
        }
    }
票数 2
EN

Stack Overflow用户

发布于 2012-02-13 02:04:17

尝试以下代码部分:

代码语言:javascript
复制
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);
        }
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9251112

复制
相关文章

相似问题

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