Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 拒绝非数字字符_Java - Fatal编程技术网

Java 拒绝非数字字符

Java 拒绝非数字字符,java,Java,这个小东西快把我累死了。我是一名Java新手,一直在尝试各种可能的方法,但似乎什么都不管用 我只希望程序拒绝非数字字符串,或者在键盘上按下时忽略字母 import java.util.Scanner; public class practice7 { public static void main(String[] args) { System.out.println(" Wlecome to the Magellan School student ass

这个小东西快把我累死了。我是一名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
我尝试了这里给出的所有答案,但每次我写信时,我都会得到这样的答案:

请输入您的学生ID:ee
线程“main”java.util.InputMismatchException中出现异常
位于java.util.Scanner.throwFor(Scanner.java:909)
下一步(Scanner.java:1530)
位于java.util.Scanner.nextInt(Scanner.java:2160)
位于java.util.Scanner.nextInt(Scanner.java:2119)
在practice7.main(practice7.java:11)
Java结果:1
生成成功(总时间:4秒)***
您可以使用

while (!input.matches("[0-9]+"))
{ System.out.print("Error, invalid input. Try Again:  "); input = sc.nextInt(); }
它使用的是的方法<代码>[0-9]+是一个,您可以使用异常找到对它的解释和演示。

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();
在try{}catch(IOException e){}块中处理它只需查看问题F**ng Hll!!这本可以让我像永远一样!它起作用了,而且非常简单。我喜欢,谢谢
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();