好吧,这件小事让我很生气。我是 Java 的新手,一直在尝试各种可能的可能性,但似乎没有任何效果。
我只希望程序拒绝非数字字符串,或者在键盘上按下时忽略字母。
import java.util.Scanner;
public class practice7 {
public static void main(String[] args) {
System.out.println(" Wlecome to the Magellan School student assistant \n\n");
System.out.print("Please Enter your Student ID: ");
Scanner sc = new Scanner(System.in);
Scanner NS = new Scanner(System.in);
int ID = sc.nextInt();
//PRETTY SURE IT GOES HERE...
//rest of program
我已经尝试了这里给出的所有答案,但每次写信时我都会得到这个:
Please Enter your Student ID: ee
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at practice7.main(practice7.java:11)
Java Result: 1
BUILD SUCCESSFUL (total time: 4 seconds)***
最佳答案
你可以使用
while (!input.matches("[0-9]+"))
{ System.out.print("Error, invalid input. Try Again: "); input = sc.nextInt(); }
使用 String
的 .matches(String regex)
方法。 [0-9]+
是 regex
,你可以找到here的解释和演示。 .
关于java - 拒绝非数字字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20546204/