CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 15 of 15

Thread: java error

  1. #1
    Join Date
    Aug 2009
    Posts
    52

    java error

    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

  2. #2
    Join Date
    Apr 2009
    Location
    TR
    Posts
    97

    Re: java error

    Quote Originally Posted by hugo84 View Post
    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/...Exception.html

    Please use code tags like this :
    [SIGPIC][/SIGPIC]
    Code Your Dreams

  3. #3
    Join Date
    Aug 2009
    Posts
    52

    Re: java error

    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.

  4. #4
    Join Date
    Apr 2009
    Location
    TR
    Posts
    97

    Re: java error

    Quote Originally Posted by hugo84 View Post
    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..

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

    Please use code tags like this :
    [SIGPIC][/SIGPIC]
    Code Your Dreams

  5. #5
    Join Date
    Aug 2009
    Posts
    52

    Re: java error

    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.

    Code:
       
             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

  6. #6
    Join Date
    Apr 2009
    Location
    TR
    Posts
    97

    Re: java error

    you can catch exception like that..write in catch blog what u want after exception..
    Code:
      
    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
    Last edited by holestary; September 15th, 2009 at 09:11 AM.

    Please use code tags like this :
    [SIGPIC][/SIGPIC]
    Code Your Dreams

  7. #7
    Join Date
    Aug 2009
    Posts
    52

    Re: java error

    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.

  8. #8
    dlorde is offline Elite Member Power Poster
    Join Date
    Aug 1999
    Location
    UK
    Posts
    10,163

    Re: java error

    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.
    Last edited by dlorde; September 15th, 2009 at 10:35 AM.
    Please use [CODE]...your code here...[/CODE] tags when posting code. If you get an error, please post the full error message and stack trace, if present.

  9. #9
    Join Date
    Aug 2009
    Posts
    52

    Re: java error

    Quote Originally Posted by dlorde View Post
    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

    Code:
    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

  10. #10
    Join Date
    May 2009
    Location
    Lincs, UK
    Posts
    298

    Re: java error

    With a Scanner you can check the token before reading it:
    Code:
    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.
    Last edited by jcaccia; September 15th, 2009 at 11:03 AM.

  11. #11
    Join Date
    Aug 2009
    Posts
    52

    Re: java error

    Quote Originally Posted by jcaccia View Post
    With a Scanner you can check the token before reading it:
    Code:
    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?

  12. #12
    Join Date
    May 2009
    Location
    Lincs, UK
    Posts
    298

    Re: java error

    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).

  13. #13
    dlorde is offline Elite Member Power Poster
    Join Date
    Aug 1999
    Location
    UK
    Posts
    10,163

    Re: java error

    Quote Originally Posted by hugo84 View Post
    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
    Please use [CODE]...your code here...[/CODE] tags when posting code. If you get an error, please post the full error message and stack trace, if present.

  14. #14
    Join Date
    Apr 2009
    Location
    TR
    Posts
    97

    Smile Re: java error

    Quote Originally Posted by hugo84 View Post
    .... 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.. it may be hard to say correctly after years

    Please use code tags like this :
    [SIGPIC][/SIGPIC]
    Code Your Dreams

  15. #15
    Join Date
    Aug 2009
    Posts
    52

    Re: java error

    Quote Originally Posted by holestary View Post
    in my first java year i was saying if loop too..and some of my friends says still.. it may be hard to say correctly after years
    lols.. thats my amateur style.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured