How to get input via command line in Java?

java

Solution

You might want to use the Scanner class: java.util.Scanner

The basic setup is simple:

Scanner scan = new Scanner(System.in);
int number = scan.nextInt();

This sets up a scanner object and makes the scanner get an integer from the default input stream. However, this doesn't check to see if the user entered "good data". It will cause errors if the user enters anything other than a number. You might want to include a loop until the user enters valid data.

Here's the same code, but with error checking:

Scanner scan = new Scanner(System.in);
boolean validData = false;
int number=0;
do{
    System.out.println("Enter a Number");
    try{
        number = scan.nextInt();//tries to get data. Goes to catch if invalid data
        validData = true;//if gets data successfully, sets boolean to true
    }catch(InputMismatchException e){
        //executes when this exception occurs
        System.out.println("Input has to be a number. ");
    }
}while(validData==false);//loops until validData is true

This program will ask the user to enter a number. If the user enters bad data, an InputMismatchException is thrown, taking the program to the catch clause and skiping setting validData to true. This loops until valid data is entered.

Hope this helps.

Problem

I currently have this code that needs user input to pseudo-ify some words to send out and commit obfuscation on the integer later. I just need to get the user input. Anyone have a good source of api to get this from? I think I should be looking for System. commands. Thanks in advance :)

Original source