拒绝非数字字符

时间:2013-12-12 14:30:07

标签: java

这个小东西杀了我。我是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)***

3 个答案:

答案 0 :(得分:2)

您可以使用

while (!input.matches("[0-9]+"))
{ System.out.print("Error, invalid input. Try Again:  "); input = sc.nextInt(); }

使用String.matches(String regex)方法。 [0-9]+regex,您可以找到here的解释和演示。

答案 1 :(得分:1)

使用例外:

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();

答案 2 :(得分:0)

// Will throw an exception if String id cannot be parsed into an integer.
int idNum = Integer.valueOf(id);