Hi im trying to check if n is an integer if not i would show an error msg and alert the user to input an integer number again. I tried to use if (n%1==0) but whenever i type a number like 45.2 i would get an error.
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:840)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextInt(Scanner.java:2091)
at java.util.Scanner.nextInt(Scanner.java:2050)
at P2.main(P2.java:8)
Why is this so?? why dosent it go to the else statement and prompt the user to reenter the number.
Code:
import java.util.Scanner;
class test {
public static void main(String[] args) {
Scanner cc= new Scanner(System.in);
System.out.println("Enter a number:");
int n = cc.nextInt();
do{
if (n%1==0){
System.out.println( times( n ) );
System.out.println("\nEnter the next number:");
n = cc.nextInt();
}
else if (n%1!=0) {
System.out.println("\nEnter a number:");
n = cc.nextInt();}
}//end do
while(n != -1);
System.out.println("Program Terminated");
}//end while
public static int times( int n )
{
return n * n;
}//end times
}//end class

