好吧,这件小事杀了我。我是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)***
最佳答案
使用异常:
int input = 0;
Boolean ready = false;
while(!ready){
try{
System.out.print("Please Enter your Student ID (Numbers Only): ");
Scanner in = new Scanner(System.in);
input = in.nextInt();
ready=true;
}catch(IOException e){
System.out.err("that was not a number");
}
}
// now we have input of integer numbers
doRestOfProgram();
你甚至可以做
String input = "nothing";
while(!input.matches("[0-9]+"))
{
System.out.print("Please Enter your Student ID (Numbers Only): ");
Scanner in = new Scanner(System.in);
input = in.nextLine();
}
// now we have input of string numbers
doRestOfProgram();
关于java - 拒绝非数字字符,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20546204/