Click to See Complete Forum and Search --> : java error


hugo84
September 15th, 2009, 08:29 AM
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.



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

holestary
September 15th, 2009, 08:41 AM
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.


because 45.2 isn't an integer..it is float type..you want an integer input but you put float..it is a RuntimeException..

http://java.sun.com/j2se/1.5.0/docs/api/java/util/InputMismatchException.html

hugo84
September 15th, 2009, 08:46 AM
Yes. I understand, so how can i do a check on my codes to allow user to input again upon a float being typed in.

holestary
September 15th, 2009, 08:53 AM
Yes. I understand, so how can i do a check on my codes to allow user to input again upon a float being typed in.

use try-catch..


try
{
.....
}
catch ( InputMismatchException inputMismatchException )
{
....
}

hugo84
September 15th, 2009, 09:07 AM
This is what i did. But it doesnt allow me to continue the program for user to input again. it just ends there with the error.


do{

try{
System.out.println( times( n ) );
System.out.println("\nEnter the next number:");
n = cc.nextInt();

}

catch ( InputMismatchException inputMismatchException ) {
System.out.println("\nError enter number again:");
n = cc.nextInt();
}

}//end do

while(n != -1);
System.out.println("Program Terminated");

}//end while

holestary
September 15th, 2009, 09:08 AM
you can catch exception like that..write in catch blog what u want after exception..


import java.util.Scanner;
import java.lang.Exception;

class test {

public static void main(String[] args) {
Scanner cc= new Scanner(System.in);
System.out.println("Enter a number:");
try{
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);
}catch(Exception ex)
{
System.out.println("Wrong Entry");
}
System.out.println("Program Terminated");

}//end while


public static int times( int n )
{
return n * n;
}//end times
}//end class

hugo84
September 15th, 2009, 09:23 AM
Hmm.. Dosent work the program will print wrong entry and terminate. What i wanted was the user keep inputting another value until sentinel reaches -1. I want it to prompt wrong entry and for the user to input another value again.

dlorde
September 15th, 2009, 10:30 AM
Put the 'try...catch' inside the 'do' loop. Put cc.next() in the 'catch' block to clear the invalid input. Remove all the duplicate n = cc.nextInt() lines from inside the loop and replace them with a single one just before the end of the loop (i.e. after the end of the 'catch' block).

Think about what you've written. n % 1 == 0 is a pointless arithmetic expression which will always be true when n is an int, because n % 1 will always be 0.

Experience is a poor teacher: it gives its tests before it teaches its lessons...
Anon.

hugo84
September 15th, 2009, 10:52 AM
Put the 'try...catch' inside the 'do' loop. Put cc.next() in the 'catch' block to clear the invalid input. Remove all the duplicate n = cc.nextInt() lines from inside the loop and replace them with a single one just before the end of the loop (i.e. after the end of the 'catch' block).

Think about what you've written. n % 1 == 0 is a pointless arithmetic expression which will always be true when n is an int, because n % 1 will always be 0.

Experience is a poor teacher: it gives its tests before it teaches its lessons...
Anon.

hmm. Ur right. This is what i changed to according to ur specs. Hmm im still getting Exception in thread "main" java.util.InputMismatchException errors when i type in a double value eg 43.2


import java.util.Scanner;
import java.lang.Exception;

class test {

public static void main(String[] args) {
Scanner cc= new Scanner(System.in);
System.out.println("Enter a number:");
int n = sc.nextInt();

do{
try{
System.out.println( times( n ) );
System.out.println("\nEnter the next number:");
// n = cc.nextInt();
}

catch(Exception ex)
{
cc.next();
} 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

jcaccia
September 15th, 2009, 10:58 AM
With a Scanner you can check the token before reading it:
Scanner sc = new Scanner(System.in);
int n;
do {
System.out.append("Enter a number: ");
if (sc.hasNextInt()) {
n = sc.nextInt();
break;
} else {System.out.format("%nERROR: %s is not an integer number!%n%n", sc.nextLine());}
} while (true);
This will loop until the user types an integer number, rejecting strings or other numbers that cannot be read as integer.

hugo84
September 15th, 2009, 11:40 AM
With a Scanner you can check the token before reading it:
Scanner sc = new Scanner(System.in);
int n;
do {
System.out.append("Enter a number: ");
if (sc.hasNextInt()) {
n = sc.nextInt();
break;
} else {System.out.format("%nERROR: %s is not an integer number!%n%n", sc.nextLine());}
} while (true);
This will loop until the user types an integer number, rejecting strings or other numbers that cannot be read as integer.

Nice!. 1 Question i did a test and put sc.nextInt() in the else loop.. The output would come out an error mismatch type. WHereas if i put sc.next() or sc.nextLine the error wont appear it will just go to the error msg. Why is this so? why wouldnt sc.nextInt work as usual as well?

is it because if you put sc.nextInt it will expect an INT value only? therefore the error. Whereas when u put sc.next() its a String? so 43.5 would not give an error mismatch?

jcaccia
September 15th, 2009, 11:53 AM
Exactly, nextInt() expects to get an integer number, if the next token available is not then it raises the exception, while next() expects a String, so any kind of input is ok.

The difference between next() and nextLine() is that the former will get the next token only and the latter everything to the end of the line.

I originally had next() for the error message, but nextLine() works better. This piece of code needs to be improved a bit to make it work with more than one value in the same line (for instance if the user types "43.5 123"), allowing you to use next() to discard the invlaid input (43.5) and procede to read the next token (123).

dlorde
September 15th, 2009, 01:21 PM
hmm. Ur right. This is what i changed to according to ur specs. Hmm im still getting Exception in thread "main" java.util.InputMismatchException errors when i type in a double value eg 43.2
Yes, I simplified it but didn't finish it because I thought you might like to get it working yourself... OK, declare 'n' before the loop, setting it to 0. Move n = cc.nextInt(); to the start of the loop. Spend some time stepping through the code so you know how it works.

When you use classes you are unfamiliar with, always read the Javadocs to see what they can do and how they should be used. That's what the Javadocs are there for. You'll often find that the writers of the class wanted to do the same thing you want to do, and provided a method to do just that.

The value of a prototype is in the education it gives you, not in the code itself...
A. Cooper

holestary
September 15th, 2009, 02:42 PM
.... i did a test and put sc.nextInt() in the else loop.....
in my first java year i was saying if loop too..and some of my friends says still..:D it may be hard to say correctly after years ;)

hugo84
September 16th, 2009, 07:55 AM
in my first java year i was saying if loop too..and some of my friends says still..:D it may be hard to say correctly after years ;)

lols.. thats my amateur style.