多扫描器输入:当前选择块的迭代验证

m4pnthwp  于 2021-07-11  发布在  Java
关注(0)|答案(1)|浏览(285)

我正在尝试验证多个扫描仪输入与配对 If-Else 在单个while循环中阻塞。我感兴趣的行为是对当前的验证 If-Statement 请求用户重新输入输入或转到后续的输入/选择块。
现在,我正在使用 continue 返回while循环开头的关键字。用一个 do...while 你觉得这更合适吗?谢谢您。

while (count < numCars) {
        System.out.println("Enter car type");
        String name = scanner.next();
        if (name.matches(".*\\d")) {
            System.out.println("Name entry cannot contain numbers");
            continue;
        } else {
            // re-enter name
        }
        System.out.println("Enter max speed");
        int maxSpeed = scanner.nextInt();
        if (maxSpeed == 100 || maxSpeed > 100) {
            System.out.println("Max speed is not valid. Please re-enter");
            continue;
        } else {
            // re-enter age
            count++;
    }
}
vdzxcuhz

vdzxcuhz1#

每个块的功能都可以通过 while 而不是 if-else 声明。我还以更好/更有组织的方式构建了您的代码:

int count = 0, numCars = 3;  // Example value
String name;
int maxSpeed;

while (count < numCars) {
    System.out.print("Enter car type: ");
    name = scanner.next();
    scanner.nextLine();     // Cleans the buffer

    while (name.matches(".*\\d")) {
        System.out.println("Name entry cannot contain numbers.");
        System.out.print("Enter car type: ");
        name = scanner.next();
        scanner.nextLine();     // Cleans the buffer
    }

    System.out.print("Enter max speed: ");
    maxSpeed = scanner.nextInt();

    while (maxSpeed >= 100) {
        System.out.println("Max speed is not valid. Please re-enter.");
        System.out.print("Enter max speed: ");
        maxSpeed = scanner.nextInt();
    }

    count++;      
}

相关问题