使用Scanner-java进行while循环时的两次检查



im试图用while循环进行两次检查:

1) 如果用户输入的不是int,则显示"错误"

2) 一旦用户输入int,如果是一位数字,则显示"仅两位数字"并保持循环,直到输入两位数字int为止(因此也应使用if)

目前我只完成了第一部分:

    Scanner scan = new Scanner(System.in);
    System.out.println("Enter a number");
    while (!scan.hasNextInt()) {
        System.out.println("error");
        scan.next();
    }

但是,如果可能的话,我希望在中同时进行两次检查,一次while循环。

这就是我被困的地方。。。

因为您已经有了两个答案。这似乎是一种更干净的方法。

Scanner scan = new Scanner(System.in);
String number = null;
do {
    //this if statement will only run after the first run.
    //no real need for this if statement though.
    if (number != null) {
        System.out.println("Must be 2 digits");
    }
    System.out.print("Enter a 2 digit number: ");
    number = scan.nextLine();
    //to allow for "00", "01". 
} while (!number.matches("[0-9]{2}")); 
System.out.println("You entered " + number);

如上所述,您应该始终将输入作为字符串,然后尝试并将其解析为int

package stackManca;
import java.util.Scanner;
public class KarmaKing {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String input = null;
        int inputNumber = 0;
        while (scan.hasNextLine()) {
            input = scan.next();
            try {
                inputNumber = Integer.parseInt(input);
            } catch (Exception e) {
                System.out.println("Please enter a number");
                continue;
            }
            if (input.length() != 2) {
                System.out.println("Please Enter a 2 digit number");
            } else {
                System.out.println("You entered: " + input);
            }
        }
    }
}

首先将输入作为字符串。如果它可以转换为Int,那么你可以进行检查,否则说2位数是可以接受的。如果它不能转换为数字,则抛出一个错误。所有这些都可以在一个while循环中完成。你想得到一个"你想继续吗?"的提示,并检查答案是否为"是"/"否"。相应地从while循环中断。

要将其作为一个循环,它比两个循环更混乱

int i = 0;
while(true)
{
    if(!scan.hasNextInt())
    {
        System.out.println("error");
        scan.next();
        continue;
    }
    i = scan.nextInt();
    if(i < 10 || >= 100)
    {
        System.out.println("two digits only");
        continue;
    }
    break;
}
//do stuff with your two digit number, i

vs具有两个环路

int i = 0;
boolean firstRun = true;
while(i < 10 || i >= 100)
{
    if(firstRun)
        firstRun = false;
    else
        System.out.println("two digits only");
    while(!scan.hasNextInt())
    {
        System.out.println("error");
        scan.next();
    }
    i = scan.nextInt();
}
//do stuff with your two digit number, i

最新更新