天天看点

java 限制输入,在Java中,您可以将输入限制为只能输入数字或只能输入一定数量的数字吗?...

java 限制输入,在Java中,您可以将输入限制为只能输入数字或只能输入一定数量的数字吗?...

In Java can you limit the input using the scanner to where only a certain types such as numbers or letters can be entered. Also can you limit input to a certain amount of characters that can be entered?

解决方案

As mentioned in the comments you cannot do that however you could check if the input was a number and less than a certain amount of character using something like the code below, prompting the user if their input is invalid:

import java.util.Scanner;

class Main {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

final int MAX_LENGTH = 4;

int num = 0;

System.out.print("Enter a number: ");

scanner:

while(scanner.hasNext()) {

if(scanner.hasNextInt()){

num = scanner.nextInt();

if(String.valueOf(num).length() <= MAX_LENGTH) {

break scanner;

} else {

System.out.println("ERROR: Input number was too long");

System.out.print("Enter a number: ");

}

} else {

System.out.println("ERROR: Invalid Input");

System.out.print("Enter a number: ");

scanner.next();

}

}

System.out.println("Valid input! You entered: " + num + ", a number less than or equal to " + MAX_LENGTH + " characters long");

}

}

Try it here!

Example Usage:

Enter a number: 123sdf

ERROR: Invalid Input

Enter a number: 1234234

ERROR: Input number was too long

Enter a number: 1234

Valid input! You entered: 1234, a number less than or equal to 4 characters long