1

Well this little thing is killing me. I am quite a rookie in Java and, have been trying every possible possibility out there and nothing seems to work.

I just want the program to either reject non numerical strings, or ignore letters when pressed on keyboard.

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

I have tried all the answers given here, but every time I write letters I get this:

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)***
The Guy with The Hat
  • 9,689
  • 7
  • 51
  • 69
eneko
  • 323
  • 3
  • 14
  • 1
    Just take a look on http://stackoverflow.com/questions/2912817/how-to-use-scanner-to-accept-only-valid-int-as-input question – amukhachov Dec 12 '13 at 14:39

3 Answers3

2

You can use

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

Which uses String's .matches(String regex) method. [0-9]+ is a regex, which you can find an explanation and demonstration of here.

The Guy with The Hat
  • 9,689
  • 7
  • 51
  • 69
1

Using exceptions:

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

you could even do

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();
wrossmck
  • 328
  • 8
  • 21
  • F***ng H*ll!! This could have taken me like forever! IT WORKS, and it is so sinple. Love it, THANKS – eneko Dec 12 '13 at 15:09
0
// Will throw an exception if String id cannot be parsed into an integer.
int idNum = Integer.valueOf(id);
Tim B
  • 38,707
  • 15
  • 73
  • 123