Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 21 of 21

Thread: Try Catch Problems

  1. #1
    Member
    Join Date
    Jan 2012
    Posts
    65
    My Mood
    Happy
    Thanks
    12
    Thanked 0 Times in 0 Posts

    Default Try Catch Problems

    So, I've messed with this program the last few days and I still am having trouble with it. The problem is it keeps crashing. The program is supposed to ask the user to input a decimal number. If the input is a string or a negative number, then it should spit out some output asking the user to input a decimal number again and again until they do.

    import java.util.Scanner;
     
    public class decimalNumber {
    	public static void main(String[] args) {
    		Scanner Input = new Scanner(System.in);
     
    		Double dec;
    		double x = 0;
    		boolean valid = true;
     
    		System.out.println("Enter a decimal number: ");
    		do {
    			try {
    				dec = Input.nextDouble();
    				valid = true;
     
    			}
    			catch (java.util.InputMismatchException e) {
    				System.out.println("Invalid inches value. Must be a decimal number.");
    				dec = Input.nextDouble();
    			}
    			if (dec <= 0) {
    				System.out.println("Please enter a positive number.");
    				dec = Input.nextDouble();
    			}
    			else {
    				System.out.println(dec);
    			}
     
    	}while(!valid);
    		System.out.println("You entered " + dec + ".");
    }
     
    }
    Last edited by Nuggets; March 23rd, 2012 at 02:07 PM.


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,930
    Thanks
    55
    Thanked 2,353 Times in 2,324 Posts

    Default Re: Try Catch Problems

    What is the code currently doing that is not what you want?
    I see it catches some bad input and prints out a message.
    Then what? Do you want to go back to the beginning of the loop and get a new input?
    Use the continue statement to do that.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Member
    Join Date
    Jan 2012
    Posts
    65
    My Mood
    Happy
    Thanks
    12
    Thanked 0 Times in 0 Posts

    Default Re: Try Catch Problems

    Modified that last code a bit. I've got two problems. One, I don't know how to continue the loop so that when the user repeatedly enters the wrong input, it keeps asking again and again. My code just tells the user one time that they have entered the wrong input, then it will accept the second input even though it was wrong. I want it to continue looping until the right input has been entered.
    My second question is if I wanted to add another input in, say an int instead of a double, how would I implement that into my try catch? So, I would have my original system.out.print "Enter a decimal number: " and then I would have another system.out.print asking the user to "Enter an integer: " after they input a decimal number. I want the exception phrases of the integer input to be the same as the decimal input. Example, "Invalid decimal number. Please enter a positive number." and for the integer input, "Invalid integer. Please enter a positive number."
    import java.util.Scanner;
     
    public class decimalNumber {
    	public static void main(String[] args) {
    		Scanner Input = new Scanner(System.in);
     
    		String dec = null;
    		double x = 0;
    		int i = 0;
     
     
    		boolean valid = true;
     
    		System.out.println("Enter a decimal number: ");
     
    			try {
    				dec = Input.next();
    				double i1 = Double.parseDouble(dec);
     
    				if (i1 <= 0) {
    					System.out.println("Invalid decimal number. Please enter a positive number.");
    					dec = Input.next();
     
    				}
    				else  {
    					System.out.println();
    				}
     
    			}
    			catch (Exception e) {
    				System.out.println("Invalid value. Must be a decimal number.");
    				dec = Input.next();
    			}
    			System.out.println("You entered the decimal number " + dec);
     
    	}
     
    }

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,930
    Thanks
    55
    Thanked 2,353 Times in 2,324 Posts

    Default Re: Try Catch Problems

    how to continue the loop
    Use the continue statement.
    if I wanted to add another input
    Use a separate try catch if you are asking for new data.
    If you don't understand my answer, don't ignore it, ask a question.

  5. The Following User Says Thank You to Norm For This Useful Post:

    Nuggets (March 26th, 2012)

  6. #5
    Member
    Join Date
    Jan 2012
    Posts
    65
    My Mood
    Happy
    Thanks
    12
    Thanked 0 Times in 0 Posts

    Default Re: Try Catch Problems

    Quote Originally Posted by Norm View Post
    Use the continue statement.

    Use a separate try catch if you are asking for new data.
    So if I had a string input, an integer input, and a double input, I would need to make 3 separate try catch statements for each one? Also, I read up a little on the continue statement, and when I tried putting it in my code, it gave an error saying I can't have it outside a loop. Even though it was in my if loop inside my try catch statement.

  7. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,930
    Thanks
    55
    Thanked 2,353 Times in 2,324 Posts

    Default Re: Try Catch Problems

    You shouldn't need a try{} catch around a String, there is no conversion being done that could it
    gave an error saying I can't have it outside a loop.
    Please post your code with the error.
    If you don't understand my answer, don't ignore it, ask a question.

  8. #7
    Member
    Join Date
    Jan 2012
    Posts
    65
    My Mood
    Happy
    Thanks
    12
    Thanked 0 Times in 0 Posts

    Default Re: Try Catch Problems

    I modified my code again. This time I inserted an integer input. My code does not work as it should though. This is an example of the output for this code.
    Enter a decimal number:
    8.3
    Invalid decimal number. Please enter a positive number. //why is it an error?
    hi //reads in the wrong input
    Enter an integer:
    -1938
    Invalid Integer value. Please enter a positive number. //this seems to be right
    hi //again reads in the wrong input
    You entered the decimal number hi and an integer number hi //output is wrong.


    import java.util.Scanner;
     
    public class bodyMassIndex {
    	public static void main(String[] args) {
    		Scanner Input = new Scanner(System.in);
     
    		String integ = null;
    		String dec = null;
    		int i = 0;
    		boolean valid = true;
     
    		System.out.println("Enter a decimal number: ");
    		do {
    			try {
    				dec = Input.next();
    				double x1 = Double.parseDouble(dec);
     
    				if (i<=0) {
    					System.out.println("Invalid decimal number. Please enter a positive number.");
    					dec = Input.next();
    				}
    				else  {
    					System.out.println();
    					valid = true;
    				}
     
    			}
    			catch (Exception e) {
    				System.out.println("Invalid value. Must be a decimal number.");
    				dec = Input.next();
    			}
     
    			System.out.println("Enter an integer: ");
     
    			try {
    				integ = Input.next();
    				double i1 = Integer.parseInt(integ);
     
    				if (i1 <= 0) {
    					System.out.println("Invalid Integer value. Please enter a positive number.");
    					integ = Input.next();
     
    				}
    				else  {
    					System.out.println();
    				}
     
    			}
    			catch (Exception e) {
    				System.out.println("Invalid Integer value. Must be a whole number.");
    				dec = Input.next();
    			}
    			System.out.println("You entered the decimal number " + dec + " and an integer number " + integ);
    		}while(valid);
    	}
     
    }

  9. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,930
    Thanks
    55
    Thanked 2,353 Times in 2,324 Posts

    Default Re: Try Catch Problems

    For debugging so you see the error message, add a call to e.printStackTrace() in the catch block.

    Print out the values that you read in and the values of the variables that you are testing in the if statements.
    Last edited by Norm; March 25th, 2012 at 11:16 AM.
    If you don't understand my answer, don't ignore it, ask a question.

  10. #9
    Member
    Join Date
    Jan 2012
    Location
    Hellas
    Posts
    284
    Thanks
    11
    Thanked 59 Times in 57 Posts

    Default Re: Try Catch Problems

    Hello Nuggets!
    You have defined and initialized variable i (i = 0) which never changes its value.
    In your first try...catch block you have:
    		if (i<=0) {
    			System.out.println("Invalid decimal number. Please enter a positive number.");
    			dec = Input.next();
     
                    }
    Therefore the print statement will always execute since i is always 0. Maybe you want to test your
    double x1 = Double.parseDouble(dec);
    in your if statement.
    And also your boolean variable valid should change its value to false at some time, otherwise your loop will be infinite.
    Hope it helps.

  11. The Following User Says Thank You to andreas90 For This Useful Post:

    Nuggets (March 26th, 2012)

  12. #10
    Member
    Join Date
    Jan 2012
    Posts
    65
    My Mood
    Happy
    Thanks
    12
    Thanked 0 Times in 0 Posts

    Default Re: Try Catch Problems

    Modified the code again. Everything seems to be working except I need it to keep checking whether the input is correct or not. It throws the exception once, then it will accept it the second time an "Invalid" message appears. For example,

    Enter a decimal number:
    lll
    Invalid value. Must be a decimal number.
    -19382
    Enter an integer:
    -83
    Invalid Integer value. Please enter a positive number.
    hii
    You entered the decimal number -19382 and an integer number hii //see it keeps accepting the wrong input
    How would I throw an exception every time there is a wrong input instead of just once?

    import java.util.Scanner;
     
    public class bodyMassIndex {
     
    	public static void main(String[] args) {
    		Scanner Input = new Scanner(System.in);
     
    		String integ = null;
    		String dec = null;
    		boolean valid = true;
     
    		System.out.println("Enter a decimal number: ");
     
    	 do {
    			try {
    				dec = Input.next();
    				double x1 = Double.parseDouble(dec);
     
     
    				if (x1<=0) {
    					System.out.println("Invalid decimal number. Please enter a positive number.");
    					valid = false;
    					dec = Input.next();
    				}
    				else  {
    					System.out.println();
    					valid = true;
    				}
     
    			}
    			catch (Exception e) {
    				System.out.println("Invalid value. Must be a decimal number.");
    				valid = false;
    				dec = Input.next();
    			}
     
    			System.out.println("Enter an integer: ");
     
    			try {
    				integ = Input.next();
    				double i1 = Integer.parseInt(integ);
     
    				if (i1 <= 0) {
    					System.out.println("Invalid Integer value. Please enter a positive number.");
    					valid = false;
    					integ = Input.next();
     
    				}
    				else  {
    					System.out.println();
    				}
     
    			}
    			catch (Exception e) {
    				System.out.println("Invalid Integer value. Must be a number.");
    				valid = false;
    				dec = Input.next();
    			}
    			System.out.println("You entered the decimal number " + dec + " and an integer number " + integ);
    		} while(!valid);
    	}
    }

  13. #11
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,930
    Thanks
    55
    Thanked 2,353 Times in 2,324 Posts

    Default Re: Try Catch Problems

    Wrap every prompt/input/conversion group in its own loop and in the loop have a try/catch block.
    Stay in the loop until you have good data, then exit that loop and enter the next loop for the next piece of data.
    If you don't understand my answer, don't ignore it, ask a question.

  14. #12
    Member
    Join Date
    Jan 2012
    Posts
    65
    My Mood
    Happy
    Thanks
    12
    Thanked 0 Times in 0 Posts

    Default Re: Try Catch Problems

    Modified code again. This time I put a do loop around each try catch block. Now, it does repeat the instances asking the user to input the right code over and over. But I must type the input twice for it to read. Why is that? Example of output:

    Enter a decimal number:
    -29
    Invalid decimal number. Please enter a positive number.
    lala // why did it ignore this input?
    lala // had to enter it twice for the program to read it.
    Invalid value. Must be a decimal number.


    import java.util.Scanner;
     
    public class bodyMassIndex {
     
    	public static void main(String[] args) {
    		Scanner Input = new Scanner(System.in);
     
    		String dece;
    		String integ = null;
    		String dec = null;
    		boolean valid = true;
     
    		System.out.println("Enter a decimal number: ");
     
     
    		do {
    			try {
    				dec = Input.next();
    				double x1 = Double.parseDouble(dec);
     
     
    				if (x1<=0) {
    					System.out.println("Invalid decimal number. Please enter a positive number.");
    					valid = false;
    					dec = Input.next();
    				}
    				else  {
    					System.out.println();
    					valid = true;
     
    				}
     
    		}
    			catch (Exception e) {
    				System.out.println("Invalid value. Must be a decimal number.");
    				valid = false;
    				dec = Input.next();
    			}
    		}while(valid == false);
     
    			System.out.println("Enter an integer: ");
     
    		do {
    			try {
    				integ = Input.next();
    				double i1 = Integer.parseInt(integ);
     
    				if (i1 <= 0) {
    					System.out.println("Invalid Integer value. Please enter a positive number.");
    					valid = false;
    					integ = Input.next();
     
    				}
    				else  {
    					System.out.println();
    				}
     
    			}
    			catch (Exception e) {
    				System.out.println("Invalid Integer value. Must be a number.");
    				valid = false;
    				dec = Input.next();
    			}
    			System.out.println("You entered the decimal number " + dec + " and an integer number " + integ);
     
    		} while(valid == false);
    	}
     
    }

  15. #13
    Member
    Join Date
    Mar 2012
    Location
    United States
    Posts
    118
    My Mood
    Inspired
    Thanks
    1
    Thanked 33 Times in 31 Posts

    Default Re: Try Catch Problems

    The reason it asks twice is because your loop contains dec = input.next() twice. The only difference being that the second time it is not parsed and therefore not throwing an exception. I have looked through your different modifications and I must say I liked the first one most. Granted it did not work, it was almost there. I went ahead and made a project on my comp and got the code working nicely, I hate typing out explanations so I will use some sudocode (non syntax critical code-like text) to maybe help a bit.


    class decimalNumber {
    	main(String[] args) {
    		Scanner Input = new Scanner;
     
    		double decimal = 0;
    		int integer = 0;
                    boolean valid = false;
     
    		do {
    			try {
                                    ask user to enter a decimal
    				dec = input.nextDouble()
    				if dec <= 0 then
                                        tell user they screwed up
    				else
                                        they didn't screw up
    			            valid = true
    			}
    			catch (e) {
    				tell user they really screwed up
    				Input.next()  // this is the kind of important part, makes the Scanner move on to the next input else it will not turn out so nice.
    			}
    		}while(!valid)

    Hope this can help.


    - Michael

  16. The Following User Says Thank You to KucerakJM For This Useful Post:

    Nuggets (March 26th, 2012)

  17. #14
    Member
    Join Date
    Jan 2012
    Posts
    65
    My Mood
    Happy
    Thanks
    12
    Thanked 0 Times in 0 Posts

    Default Re: Try Catch Problems

    The problem is when I change decimal to a double instead of a string, the program crashes when I enter a string as an input. For some reason it won't catch the error, just crashes the program. My catch statement remained the same. Everything else is fine though.

  18. #15
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,930
    Thanks
    55
    Thanked 2,353 Times in 2,324 Posts

    Default Re: Try Catch Problems

    Please post the full text of the error message and the code that causes it.

    Does the exception happen outside of a try/catch block?
    If you don't understand my answer, don't ignore it, ask a question.

  19. #16
    Member
    Join Date
    Jan 2012
    Posts
    65
    My Mood
    Happy
    Thanks
    12
    Thanked 0 Times in 0 Posts

    Default Re: Try Catch Problems

    Nvm guys, I got the code working. I wasn't posting my real code btw. This program is for class and I didn't want to get in trouble if the wrong person saw it. My program works properly now. Much thanks to everyone who helped me in this thread! I will give thanks to everyone who contributed.

  20. #17
    Junior Member
    Join Date
    Mar 2012
    Posts
    3
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Try Catch Problems

    I'll attempt to piggyback on this thread with a quick catch question in case someone checks in.

    My catch(InputMismatchException e) will catch decimal inputs. I'd like the decimals to pass through. Is there a way to avoid that?

  21. #18
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,930
    Thanks
    55
    Thanked 2,353 Times in 2,324 Posts

    Default Re: Try Catch Problems

    What do you mean "decimal inputs"?
    What does "pass through" mean?

    Post some examples of input and say how you are reading & processing those inputs and what you want to happen. Post the code also.
    If you don't understand my answer, don't ignore it, ask a question.

  22. #19
    Junior Member
    Join Date
    Mar 2012
    Posts
    3
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Try Catch Problems

    Well, the loop looks like this. I'm trying to catch negative numbers and non-numbers, but it catches decimals like 5.5.
    do{
     
    		try {
     
    			error = false;
     
     
    			System.out.println("Enter a positive number");
    			number = console.nextInt();
     
    			while (number<= 0)
    			{
    				System.out.println("Invalid number value. Must be positive.");
    				number = console.nextInt();
    			}	
     
    			}
     
    		catch(InputMismatchException e)
    		{
    			error = true;
    			console.nextLine();
    			System.out.println("Invalid number value.  Must be a decimal number.");
     
    		}
     
    	} while(error);

  23. #20
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,930
    Thanks
    55
    Thanked 2,353 Times in 2,324 Posts

    Default Re: Try Catch Problems

    5.5 is a valid double number. It is not a valid int. The Scanner class has some methods whose names begin with has can be used to test what is in Scanner's buffer.
    If you don't understand my answer, don't ignore it, ask a question.

  24. The Following User Says Thank You to Norm For This Useful Post:

    theway (March 27th, 2012)

  25. #21
    Junior Member
    Join Date
    Mar 2012
    Posts
    3
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Try Catch Problems

    I knew I was missing something stupid. Thanks a ton!

Similar Threads

  1. Two Problems Try catch and If
    By Callcollect in forum What's Wrong With My Code?
    Replies: 4
    Last Post: December 19th, 2011, 07:57 AM
  2. how do i try/catch this?
    By safra in forum Exceptions
    Replies: 6
    Last Post: October 29th, 2011, 12:14 PM
  3. [SOLVED] Problems with Try/Catch Catching Wrong Exception
    By bgroenks96 in forum What's Wrong With My Code?
    Replies: 14
    Last Post: June 10th, 2011, 09:08 PM
  4. catch all
    By silverspoon34 in forum Exceptions
    Replies: 1
    Last Post: November 29th, 2009, 02:18 PM
  5. try/catch
    By rsala004 in forum Exceptions
    Replies: 5
    Last Post: July 19th, 2009, 04:20 PM