|
question regarding exceptions..
Hey,
This might be a very simple question.
I'm writing a simple program where the user is asked to enter an integer.
System.out.println("Please enter an integer");
a = scanner.nextInt();
So i'm expecting him to enter an integer, but lets say that the user didnt enter an integer instead he entered a word or anything other than an int. I need to print him a message saying "Sorry... you have to enter an integer.." and then reprompt him again to enter an integer "Please enter an integer". Basically what should i do ???
Should I write an "if statement" or should i try to catch the exception ???
I hope somebody can clarify this point.. maybe with an example.
Any help would be appreciated. Thanks alot.
Heres the code:
public class DemoProgram2{
public static void main(String[] args){
Scanner scanner;
int x; //raw date information
//create scanner for reading user keyboard input
scanner = new Scanner(System.in);
//read and int representation of the date from the keyboard
System.out.print("Enter birthday as an DDMMYYYY int and [ENTER]: ");
x = scanner.nextInt();
//output the data collected
System.out.println("Your Data");
System.out.println("=========");
System.out.println("x=" + x);
System.out.println("Your Birthday");
int day = (x - x % 1000000) / 1000000;
int month = (x%1000000 - x % 10000)/10000;
int year = x % 10000;
System.out.println(day + "/" + month + "/" + year);
}
}
|