looping with console input and try/catch block

  • (2 Pages)
  • +
  • 1
  • 2

16 Replies - 4754 Views - Last Post: 18 June 2012 - 04:13 PM Rate Topic: -----

#1 CodingInBoise  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 25
  • Joined: 16-June 12

looping with console input and try/catch block

Posted 16 June 2012 - 04:35 PM

I am a beginner programmer, and this is homework.
I have heavily commented my code to assist both myself and anyone else helping me in determining what went wrong.
I am trying to make a loop that only repeats if the user inputs inappropriate data such as letters or negative numbers. I do not understand why my boolean will not work in this case. My code runs just fine when catching letters, but it will not repeat the prompt for new data. I have tried using a do/while loop, as well as a regular while loop. The boolean value almost seems to work backwards. Thank you in advance for your time in helping me.
import java.util.*;

public class Main
{
    static Scanner console = new Scanner(System.in);
    public static void main(String[] args)
    {
        //initial declerations
        double feet;
        double inches;
        double centimeters;
        double totalInches;
        boolean end = false;//  IN THEORY  becomes true when no exeption occurs
        //  BOOLEAN DOES NOT WORK HERE FOR WHAT I WANT IT TO DO
        while(end = false)
        {
            //bring in data
            try
            {
                System.out.println("Please enter number of feet: ");
                feet = console.nextDouble();
                System.out.println("Please enter number of inches: ");
                inches = console.nextDouble();
                //convert from feet and inches to just inches
                totalInches = inches + (feet * 12);
                //convert from totalInches to centimeters
                centimeters = (totalInches * 2.54);
                //print output
                System.out.println("The length of " + feet + " feet " + inches + " inches");
                System.out.println("is equivilent to: " + centimeters + "centimeters");
                end = true;//  WHY WON'T THIS WORK ?
            }
            catch (InputMismatchException imeRef)//catch non-numerical input
            {
                System.out.println("Exception " + imeRef);
            }
        }//end of while loop
    }//end of main()
}//end of class



Is This A Good Question/Topic? 0
  • +

Replies To: looping with console input and try/catch block

#2 CasiOo  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1379
  • Posts: 3,041
  • Joined: 05-April 11

Re: looping with console input and try/catch block

Posted 16 June 2012 - 04:51 PM

You are first assigning end to false and then evaluating it
while(end = false)



It should be
while(end == false)



Or more pretty (you could change it to a positive word instead so you won't need the negation)
while(!end)


Was This Post Helpful? 1
  • +
  • -

#3 CodingInBoise  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 25
  • Joined: 16-June 12

Re: looping with console input and try/catch block

Posted 16 June 2012 - 09:08 PM

Thank you! I really appreciate the quick reply. I really made n00b mistake there.
My program goes back in now, and loops, but it is not quite right. Now that I have the loop fixed, I will probably be able to figure out what is wrong.
Was This Post Helpful? 0
  • +
  • -

#4 CodingInBoise  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 25
  • Joined: 16-June 12

Re: looping with console input and try/catch block

Posted 17 June 2012 - 02:58 PM

I have made some changes, and overall it works fine. I would like some feedback on making it better, within the scope of the assignment. (in other words, lets not get too advanced) I am also, however, a little unsatisfied with how it handles non-numerical data. I did a test run, using a negative and a letter to test for the two types of exceptions I need to handle, and here is the result: (********** is the name of the project, and it has personal information in it, mainly intended for the teacher to identify my work)

Enter number of feet and number of inches seperated by a space
-3 x
Exception java.util.InputMismatchException
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextDouble(Scanner.java:2456)
at **********.Main.main(Main.java:59)
Java Result: 1

This does not look like what I though it would say when an exception occurs. If this is what it should look like, then so be it, but I was expecting something shorter.


import java.util.*;

public class Main
{
    static Scanner console = new Scanner(System.in);
    public static void main(String[] args)
    {
        //initial declerations
        double feet, inches, centimeters, totalInches;
        boolean end = false;//  IN THEORY  becomes true when no exeption occurs
        do
        {
            //bring in data
            try
            {
                //System.out.println("Please enter number of feet: ");
                System.out.println("Enter number of feet and " +
                        "number of inches seperated by a space");
                feet = console.nextDouble();
                inches = console.nextDouble();
                if(feet < 0)//catch negative numbers
                {
                    System.out.println("Invalid entry! Please enter " +
                            "only positive numbers.");
                    System.out.println("Please re-enter number of feet " +
                            "and inches seperated by a space: ");
                    feet = console.nextDouble();
                    inches = console.nextDouble();
                }
                //convert from feet and inches to just inches
                totalInches = inches + (feet * 12);
                //convert from totalInches to centimeters
                centimeters = (totalInches * 2.54);
                //print output
                System.out.println("The length of " + feet + " feet "
                        + inches + " inches");
                System.out.println("is equivilent to: "
                        + centimeters + "centimeters");
                end = true;
            }
            catch (InputMismatchException imeRef)//catch non-numerical input
            {
                System.out.println("Exception " + imeRef);
                console.nextDouble();
            }
        }//end of do
        while(!end);
    }//end of main()
}//end of class


Thank you in advance for your time.
Was This Post Helpful? 0
  • +
  • -

#5 CasiOo  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1379
  • Posts: 3,041
  • Joined: 05-April 11

Re: looping with console input and try/catch block

Posted 17 June 2012 - 03:46 PM

What you see is the String returned by the toString() method of InputMismatchException imeRef. It is saying what it is supposed to (not very helpful for the user of the program)
Was This Post Helpful? 0
  • +
  • -

#6 CodingInBoise  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 25
  • Joined: 16-June 12

Re: looping with console input and try/catch block

Posted 17 June 2012 - 04:04 PM

View PostCasiOo, on 17 June 2012 - 03:46 PM, said:

What you see is the String returned by the toString() method of InputMismatchException imeRef. It is saying what it is supposed to (not very helpful for the user of the program)

What would you recommend to make it more helpful for the user of the program?

Also, is there anything else you would recommend in the way of changes that would make my code better?
Was This Post Helpful? 0
  • +
  • -

#7 CasiOo  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1379
  • Posts: 3,041
  • Joined: 05-April 11

Re: looping with console input and try/catch block

Posted 17 June 2012 - 04:16 PM

View PostCodingInBoise, on 17 June 2012 - 11:04 PM, said:

View PostCasiOo, on 17 June 2012 - 03:46 PM, said:

What you see is the String returned by the toString() method of InputMismatchException imeRef. It is saying what it is supposed to (not very helpful for the user of the program)

What would you recommend to make it more helpful for the user of the program?

Also, is there anything else you would recommend in the way of changes that would make my code better?


You should tell them they made an illegal input. Also I don't understand why you have this line after printing the exception:
console.nextDouble();



Wouldn't you just want to make it loop from the beginning again? or is it because you want the user to type something before it should continue? At least you are not assigning it to anything.

You are right about catching if the user inputs a negative number, but what if he does it two times in a row, then it will go through.
It could easily be solved by rearranging some of the code and changing the if statement
                if(feet >= 0)//catch negative numbers
                {
					//convert from feet and inches to just inches
					totalInches = inches + (feet * 12);
					//convert from totalInches to centimeters
					centimeters = (totalInches * 2.54);
					//print output
					System.out.println("The length of " + feet + " feet "
							+ inches + " inches");
					System.out.println("is equivilent to: "
							+ centimeters + "centimeters");
					end = true;
                } else {
				     System.out.println("Invalid entry! Please enter " +
                            "only positive numbers.");
                    System.out.println("Please re-enter number of feet " +
                            "and inches seperated by a space: ");
				}


Was This Post Helpful? 1
  • +
  • -

#8 CodingInBoise  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 25
  • Joined: 16-June 12

Re: looping with console input and try/catch block

Posted 17 June 2012 - 04:44 PM

Quote

You should tell them they made an illegal input. Also I don't understand why you have this line after printing the exception:
console.nextDouble();


My reason for putting this in is I was experimenting with ways to make my code work, and I forgot to take that one out.

For the rest of it, thank you very much. It looks like it will be quite useful. I like the way that you used the reverse of my "if" logic to better handle negatives.
Was This Post Helpful? 0
  • +
  • -

#9 CasiOo  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1379
  • Posts: 3,041
  • Joined: 05-April 11

Re: looping with console input and try/catch block

Posted 17 June 2012 - 04:49 PM

View PostCodingInBoise, on 17 June 2012 - 11:44 PM, said:

Quote

You should tell them they made an illegal input. Also I don't understand why you have this line after printing the exception:
console.nextDouble();


My reason for putting this in is I was experimenting with ways to make my code work, and I forgot to take that one out.

For the rest of it, thank you very much. It looks like it will be quite useful. I like the way that you used the reverse of my "if" logic to better handle negatives.


The same could have been made with an else statement on your existing code, but now it all comes in the order I like haha ;)
Was This Post Helpful? 0
  • +
  • -

#10 CodingInBoise  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 25
  • Joined: 16-June 12

Re: looping with console input and try/catch block

Posted 17 June 2012 - 06:00 PM

After implementing your suggestions, and some improvements of my own, the negative number error handling has been greatly improved.

My problem now is with the way that exceptions are handled when there is an InputMismatchException. If this exception happens, it causes an infinite loop. The infinite loop is of the following text:

Exception java.util.InputMismatchException
Please enter only numerical data
Enter number of feet and number of inches seperated by a space

I do not understand why it is doing this. I would appreciate any help with understanding why this works that way, and how to fix my code.

Incidentally, the line
console.nextDouble();


keeps my program from entering the infinite loop, but also prevents it from saying in the loop that I do want.

The following is a complete copy of my code:
import java.util.*;

public class Main
{
    static Scanner console = new Scanner(System.in);
    public static void main(String[] args)
    {
        //initial declerations
        double feet, inches, centimeters, totalInches;
        boolean end = false;//  IN THEORY  becomes true when no exeption occurs
        boolean firstRun = true;
        do
        {
            //bring in data
            try
            {
                if(firstRun)
                {
                System.out.println("Enter number of feet and " +
                        "number of inches seperated by a space");
                }
                feet = console.nextDouble();
                inches = console.nextDouble();
                firstRun = false;
                if(feet >= 0)//catch negative numbers
                {
                    //convert from feet and inches to just inches
                    totalInches = inches + (feet * 12);
                    //convert from totalInches to centimeters
                    centimeters = (totalInches * 2.54);
                    //print output
                    System.out.println("The length of " + feet + " feet "
                        + inches + " inches");
                    System.out.println("is equivilent to: "
                        + centimeters + "centimeters");
                    end = true;
                }
                else
                {
                    System.out.println("Invalid entry! Please enter " +
                        "only positive numbers.");
                    System.out.println("Please re-enter number of feet " +
                        "and inches seperated by a space: ");
                }
            }
            catch (InputMismatchException imeRef)//catch non-numerical input
            {
                System.out.println("Exception " + imeRef + "\nPlease enter " +
                        "only numerical data");
            }
        }//end of do
        while(!end);
    }//end of main()
}//end of class


Thank you again for your time.
Was This Post Helpful? 0
  • +
  • -

#11 CodingInBoise  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 25
  • Joined: 16-June 12

Re: looping with console input and try/catch block

Posted 18 June 2012 - 11:38 AM

I have looked around for other people who have had similar problems, and I found one possible solution. If I remove the do/while, and instead put my code into a method, then have the catch call the method, would that solve my problem of an infinite loop that prints out my error? Also, because I have not covered that part yet, is my potential solution creating a recursive method, or is this something else.

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

#12 CodingInBoise  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 25
  • Joined: 16-June 12

Re: looping with console input and try/catch block

Posted 18 June 2012 - 12:44 PM

Alright, I changed my code to work as a method that calls itself (I think that is called recursion) and it works just the same as it did when it was a do/while loop (at least it does from a user point of view). Everything is fine if it is negative numbers that need handling, but if it enters into the catch, it goes into an infinite loop. I think that this is because once invalid data is read by the try, the catch immediately activates, and throws the error. Once invalid data is there, it cannot get down to the line that would read in replacement data because the error is thrown the instant the try begins.
The real question is, how do I get around this?
Thank you!
Was This Post Helpful? 0
  • +
  • -

#13 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10397
  • View blog
  • Posts: 38,479
  • Joined: 27-December 08

Re: looping with console input and try/catch block

Posted 18 June 2012 - 12:55 PM

You shouldn't need recursion here. You're overcomplicating things. If an Exception occurs, just set your boolean flag to false, so the loop will repeat.
Was This Post Helpful? 1
  • +
  • -

#14 CodingInBoise  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 25
  • Joined: 16-June 12

Re: looping with console input and try/catch block

Posted 18 June 2012 - 01:17 PM

Okay, good to know that recursion is not the way to go. But if that is true, then what is causing my infinite loop when using my do/while approach. I get an infinitely repeating loop of the last three lines of the following test run.

Enter number of feet and number of inches seperated by a space
3 x
Exception java.util.InputMismatchException
Please enter only numerical data
Enter number of feet and number of inches seperated by a space
Exception java.util.InputMismatchException
Please enter only numerical data
Enter number of feet and number of inches seperated by a space

Here is a copy of my code:

import java.util.*;

public class Main
{
    static Scanner console = new Scanner(System.in);
    public static void main(String[] args)
    {
        //initial declerations
        double feet, inches, centimeters, totalInches;
        boolean end = false;//  IN THEORY  becomes true when no exeption occurs
        boolean firstRun = true;
        do
        {
            //bring in data
            try
            {
                if(firstRun)
                {
                System.out.println("Enter number of feet and " +
                        "number of inches seperated by a space");
                }
                feet = console.nextDouble();
                inches = console.nextDouble();
                firstRun = false;
                if(feet >= 0)//catch negative numbers
                {
                    //convert from feet and inches to just inches
                    totalInches = inches + (feet * 12);
                    //convert from totalInches to centimeters
                    centimeters = (totalInches * 2.54);
                    //print output
                    System.out.println("The length of " + feet + " feet "
                        + inches + " inches");
                    System.out.println("is equivilent to: "
                        + centimeters + "centimeters");
                    end = true;
                }
                else
                {
                    System.out.println("Invalid entry! Please enter " +
                        "only positive numbers.");
                    System.out.println("Please re-enter number of feet " +
                        "and inches seperated by a space: ");
                }
            }
            catch (InputMismatchException imeRef)//catch non-numerical input
            {
                System.out.println("Exception " + imeRef + "\nPlease enter " +
                        "only numerical data");
                end = false;
            }
        }//end of do
        while(!end);
    }//end of main()
}//end of class


My textbook has proven to be very unhelpful, and I have very few other places to turn. I appreciate any help that you can offer, and thank you for your time.
Was This Post Helpful? 0
  • +
  • -

#15 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10397
  • View blog
  • Posts: 38,479
  • Joined: 27-December 08

Re: looping with console input and try/catch block

Posted 18 June 2012 - 01:47 PM

In your catch block, add a console.nextLine(); so the buffer will start at the next line.
Was This Post Helpful? 1
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2