2 Replies - 6617 Views - Last Post: 27 June 2011 - 02:56 PM Rate Topic: -----

#1 deprosun  Icon User is offline

  • D.I.C Regular

Reputation: 0
  • View blog
  • Posts: 292
  • Joined: 16-November 10

Why my try--catch statement wont Stop? (JAVA)

Posted 27 June 2011 - 01:15 PM

I was trying to do it through try--catch statement. And I had been busting my head syntactical and logical wise to find out why my loop of try--catch statement wont stop when it gets a false statement. Here is the the output:
Type your first number: e
Invalid input! Please type an Integer. 
Type your first number: Invalid input! Please type an Integer. 
Type your first number: Invalid input! Please type an Integer. 
Type your first number: Invalid input! Please type an Integer. 
Type your first number: Invalid input! Please type an Integer. 
Type your first number: Invalid input! Please type an Integer. 
Type your first number: Invalid input! Please type an Integer. 
Type your first number: Invalid input! Please type an Integer......and so on 


here is the actual code:

import java.util.Scanner;

 

public class Addition {

 

    public static void main(String args[]) {

        Scanner input = new Scanner(System.in);
        int num1=0;

        int num2;

        int sum;
        boolean check=false;

 
        do{
        try{
            System.out.print("Type your first number: ");
            num1 = input.nextInt();
            check = true;
        }
        catch(java.util.InputMismatchException x){
            System.out.println("Invalid input! Please type an Integer. ");
            num1=0;
            check = false;
        }
        }while (check==false);

 

        System.out.print("Type your second number: ");

        num2 = input.nextInt();

        sum = num1 + num2;

       System.out.print(sum + "\n");

    }

}



Is This A Good Question/Topic? 0
  • +

Replies To: Why my try--catch statement wont Stop? (JAVA)

#2 g00se  Icon User is online

  • D.I.C Lover
  • member icon

Reputation: 2639
  • View blog
  • Posts: 11,148
  • Joined: 20-September 08

Re: Why my try--catch statement wont Stop? (JAVA)

Posted 27 June 2011 - 02:10 PM

You need to ensure that all input has been consumed, so try


            catch (java.util.InputMismatchException x) {
                System.out.println("Invalid input! Please type an Integer. ");

                num1 = 0;

                check = false;
		input.nextLine();
            }

Was This Post Helpful? 1
  • +
  • -

#3 deprosun  Icon User is offline

  • D.I.C Regular

Reputation: 0
  • View blog
  • Posts: 292
  • Joined: 16-November 10

Re: Why my try--catch statement wont Stop? (JAVA)

Posted 27 June 2011 - 02:56 PM

g00se! you are god!

Thank You!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1