使用扫描仪检查“ int”类型的多个输入

问题描述

这个问题已经在这里有了答案: 如何使用java.util.Scanner从system.in正确读取用户输入并对其进行操作? (1个答案) 3年前关闭

我正在使用java.util.Scanner从system.in获取用户输入。这是一个井字游戏。输入的是2个坐标,应该看起来像这样:1 1或1 2等,两个整数用空格隔开。我需要验证其中的每一个,例如:

It must be a non-negative number
It must be from 1-3
... etc

我已经尝试过这种方法,但这适合一个值。验证两个值(对于int类型)的最佳方法是什么?

do {
            System.out.println("Enter the coordinates: ");
            while (!scanner.hasNextInt()) {
                System.out.println("You should enter numbers!");
                scanner.next(); // this is important!
            }
            if(scanner.nextInt() > 3 || scanner.nextInt()<1 ) {
                coord1 = scanner.nextInt();
            }else{
                System.out.println();
            }
        } while (coord1 !=0);
        System.out.println("Thank you! Got " + coord1);

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)