我需要验证用户是否输入了两个整数,因此,我需要继续要求他输入,直到他提供两个整数输入.不知道如何实现它,但我想出了类似的方法,但现在很难实现判断coord1和coord2是否得到正确类型的部分.如果不是,它当然会给我数字形式的感觉:

  while (true) {
            System.out.print("Enter the coordinates: ");
            int coord1 = Integer.parseInt(scanner.next());
            int coord2 = Integer.parseInt(scanner.next());
            if (coord1 < 1 || coord1 > 3 || coord2 < 1 || coord2 > 3) {
                System.out.println("Coordinates should be from 1 to 3!");
                continue;
            } else if (cellOccupied(field, coord1, coord2)) {
                System.out.println("This cell is occupied! Choose another one!");
                continue;
            }
            break;
        }

既然我还没有学会,我能不用try/catch解决它吗?或者这是唯一的方法吗?

提前感谢您,很抱歉,因为我还在学习Java语法和验证方法.

推荐答案

你可以依靠Scanner的方法hasNextInt()nextInt(),而不是手动判断输入是否正确.

第一个将判断您的输入是否是实际的int,然后您可以继续用nextInt()读取它.有关在读取数字类型后放置nextLine()的更多详细信息,请阅读下面关于堆栈溢出的question.

在这里,我还将您的代码包含在一个示例main中.我知道你的只是一个代码片段,周围有更多的代码(例如,我没有cellOccupied方法),但我只是像这样粘贴了它,以进行最低限度的测试.此外,我还对您的用例进行了参数化.使用相同的坐标逻辑重复相同的代码来读取用户输入有点奇怪和多余.

public class Main {
    public static void main(String[] args) {
        int coord1 = 0, coord2 = 0;
        do {
            coord1 = readCoordinate("Enter first coordinate: ");
            coord2 = readCoordinate("Enter second coordinate: ");

            //Showing an error message if the coords refer to an occupied cell
            if (cellOccupied(field, coord1, coord2)) {
                System.out.println("This cell is occupied! Choose another one!");
            }
        } while (cellOccupied(field, coord1, coord2));
    }

    private static int readCoordinate(String message) {
        int coord;
        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.print(message);
            if (scanner.hasNextInt()) {
                coord = scanner.nextInt();

                //getting rid of the new line character after reading the int
                scanner.nextLine();

                //Checking coordinate value
                if (coord < 1 || coord > 3) {
                    System.out.println("Coordinates should be from 1 to 3!");
                    continue;
                }
            } else {
                //assigning an undesired value (since your coords must be between 1 and 3
                coord = 0;

                //getting rid of the wrong user input
                scanner.nextLine();

                //Showing an error message
                System.out.println("Please enter an int value");

                //Skipping directly to the loop's condition
                continue;
            }

            break;
        }

        return coord;
    }
}

另一方面,避免在循环中声明字段.

Java相关问答推荐

Java Stream,需要更新列表对象列表

如何转换Tue Feb 27 2024 16:35:30 GMT +0800 String至ZonedDateTime类型""

使用Java Streams API比较两个不同的Java集合对象和一个公共属性

现场观看Android Studio中的变化

如何打印本系列的第n项y=-(1)-(1+2)+(1+2+3)+(1+2+3+4)-(1+2+3+4+5)...Java中的(1+2+3+4...+n)

如何找到MongoDB文档并进行本地化?

测试何时使用Mockito强制转换对象会导致ClassCastException

Jenv-相同的Java版本,但带有前缀

基于接口的投影、原生查询和枚举

使用用户引入的参数生成人员数组

try 从REST API返回对象列表时出错

为什么有两种实现来检索数组类的组件类型?

视图被推出线性布局-Android

无法在Java中获取ElastiCache的AWS CloudWatch指标

如何在Spring Boot Auth服务器上正确配置CORS?

按长度排序字符串数组

如何使用命令行为Java应用程序生成烟雾测试用例

窗口启动后不久,从java.awt.Graphics disapear创建的矩形

如何在android studio中将图像的像素单位转换为平方英寸?

为什么这个printKthToLast递归(java)从头到尾开始?