Page 1 of 2 12 LastLast
Results 1 to 20 of 22
  1. #1
    Martyn is offline Member
    Join Date
    Nov 2011
    Location
    Belfast
    Posts
    37
    Rep Power
    0

    Default Multiple try & catch statements within a switch

    Hello,

    I need to insert multipile try/catch statements into a program can someone tell me the correct location for the try and catch I have tried every possible start and end point (apart from the correct one). Also can the try catch statement restart the program i.e. take the user back to the origional question before the user keyed in the error. Any help would be great. I have attched a screen shot of my code.



    .
    Multiple try & catch statements within a switch-try-catch.jpg

    ANy help would be great, thanks

    Martyn

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,882
    Rep Power
    25

    Default Re: Multiple try & catch statements within a switch

    what is the relationship between the code and the exception printout?
    The exception data does not show a line in your code. You need to post the full text of the exception message that shows where in your code the exception occurred.

    I don't think the location of the try{} catch within a switch/case statement has any relation to your problem.

    take the user back to the origional question
    You will need to put the code inside of a loop that exits only when the user has given you good data.

    For easier testing write a small program with a loop that asks the user for input, tests the input and exits the loop if the data is good. If the data is not good, stay in the loop until the data is good. Part of the testing of the data would be the catching of the InputMismatchException.

  3. #3
    Martyn is offline Member
    Join Date
    Nov 2011
    Location
    Belfast
    Posts
    37
    Rep Power
    0

    Default Re: Multiple try & catch statements within a switch

    Thanks for the reply I tried the approach of only checking the user input as opposed to having the try/catch over the whole case and it still throws up an exception Im now thinking the problem is somewhere else ive attached a screen shot showing the error.

    .
    Multiple try & catch statements within a switch-try-catch-1.jpg



    All thoughts are welcome

    Martyn

  4. #4
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,882
    Rep Power
    25

    Default Re: Multiple try & catch statements within a switch

    The exception messages says it occurred on line 39.
    Your code snapshot does not show line 39

  5. #5
    Martyn is offline Member
    Join Date
    Nov 2011
    Location
    Belfast
    Posts
    37
    Rep Power
    0

    Default Re: Multiple try & catch statements within a switch

    I hope this doesnt sound noobish but if possible It seems the try catch is working, but the program also runs the last command, gets half way through the previous command and then breaks see below

    Multiplication tables game

    1... Times tables - (select and view)
    2... Practice - (select and practice)
    3... New game - (12 random times table sums)
    4... Quit
    1
    Select times table to view (1 and 12 only)...
    6
    6 * 1 = 6
    6 * 2 = 12
    6 * 3 = 18
    6 * 4 = 24
    6 * 5 = 30
    6 * 6 = 36
    6 * 7 = 42
    6 * 8 = 48
    6 * 9 = 54
    6 * 10 = 60
    6 * 11 = 66
    6 * 12 = 72
    Multiplication tables game

    1... Times tables - (select and view)
    2... Practice - (select and practice)
    3... New game - (12 random times table sums)
    4... Quit
    1
    Select times table to view (1 and 12 only)...
    marty
    Invald, Please Enter Another Number:
    6 * 1 = 6
    6 * 2 = 12
    6 * 3 = 18
    6 * 4 = 24
    6 * 5 = 30
    6 * 6 = 36
    Exception in thread "main" java.util.InputMismatchException
    6 * 7 = 42
    6 * 8 = 48
    6 * 9 = 54
    6 * 10 = 60
    6 * 11 = 66
    6 * 12 = 72
    Multiplication tables game

    1... Times tables - (select and view)
    2... Practice - (select and practice)
    3... New game - (12 random times table sums)
    4... Quit
    at java.util.Scanner.throwFor(Scanner.java:909)
    at java.util.Scanner.next(Scanner.java:1530)
    at java.util.Scanner.nextInt(Scanner.java:2160)
    at java.util.Scanner.nextInt(Scanner.java:2119)
    at timestables.TimesTables.main(TimesTables.java:39)
    Java Result: 1

    BUILD SUCCESSFUL (total time: 15 seconds)

    Now im completly lost but all part of the learning curve lol

  6. #6
    Martyn is offline Member
    Join Date
    Nov 2011
    Location
    Belfast
    Posts
    37
    Rep Power
    0

    Default Re: Multiple try & catch statements within a switch

    Quote Originally Posted by Norm View Post
    The exception messages says it occurred on line 39.
    Your code snapshot does not show line 39
    Hi Norm thanks for replying, its somthing to do with the scanner, ile mess about with it and see what happens, ive attached the screen shot

    .


    Multiple try & catch statements within a switch-try-catch-2.jpg

    .

  7. #7
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,882
    Rep Power
    25

    Default Re: Multiple try & catch statements within a switch

    Did you do the call to nextLine() as shown on lines 40-41 following the last call to nextInt()?

  8. #8
    Martyn is offline Member
    Join Date
    Nov 2011
    Location
    Belfast
    Posts
    37
    Rep Power
    0

    Default Re: Multiple try & catch statements within a switch

    I noticed that nextLine was missing and added it into case 1 but still the same output, i even put a break; within the catch to try and stop it but it still goes on, I also tried changing the user input "choice" to the origional user input "option" and nothing changed.

  9. #9
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,882
    Rep Power
    25

    Default Re: Multiple try & catch statements within a switch

    Do some debugging by changing the call to nextInt() to a call to next() that reads a String and then print it so you can see what was entered.
    Java Code:
      String inVal = scrnr.next();  // instead of nextInt()
      System.out.println("inVal=" + inVal + "<");  // show what was read!!!
      choice = Integer.parseInt(inVal); // convert the String to an int

  10. #10
    Martyn is offline Member
    Join Date
    Nov 2011
    Location
    Belfast
    Posts
    37
    Rep Power
    0

    Default Re: Multiple try & catch statements within a switch

    Hi Norm,

    I put a try catch up at the 1st set of options then when I entered text it created a continuous loop.

    ile give the de-bugging a shot, ile post when I get it working

    Thanks again

    Martyn

  11. #11
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,882
    Rep Power
    25

    Default Re: Multiple try & catch statements within a switch

    when I entered text it created a continuous loop.
    You should post the code if you need help with it.

    Do NOT post any more images. You can not copy lines of source from an image if there needs to be references made to it.

  12. #12
    Martyn is offline Member
    Join Date
    Nov 2011
    Location
    Belfast
    Posts
    37
    Rep Power
    0

    Default Re: Multiple try & catch statements within a switch

    Hi Norm this is my code im fairly new to Java go easy

    I removed the Int, and the Line - Int didnt work and removing the line meant having to enter 5 twice to see the 5 times tables


    .................................................. ......................................


    Java Code:
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    package timestables;
    
    /**
     *
     * @author pc user
     */
    import java.util.Scanner;
    
    public class TimesTables {
    
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
    
            //Scan for user input
            Scanner scanner = new Scanner(System.in);
    
            // Variable that holds the option of the user...
            int option = 0;
            //Initialise variable for the amount of correctly answered questions
            int correctCrt = 0;
    
            int choice = 0;
    
            //Output options to user
            do {
                System.out.println("Multiplication tables game\n");
                System.out.println("1... Times tables - (select and view)");
                System.out.println("2... Practice - (select and practice)");
                System.out.println("3... New game - (12 random times table sums)");
                System.out.println("4... Quit");
    
                //read in the value choosen
                option = scanner.nextInt();
                //need to do this just after reading an int
                scanner.nextLine();
    
                //Initialise option selection
                switch (option) {
    //Code Part 1 ................................................................................................
    
                    case 1://Initialise option 1 if user inputs option 1
    
                        //Output statement below once option 1 hase
                        System.out.println("Select times table to view (1 and 12 only)...");
    
                        try {
    
                            choice = scanner.nextInt();
                            //need to do this just after reading an int
                            scanner.nextLine();
    
                        } catch (Exception ex) {
                            System.out.println("Invald, Please Enter Another Number: ");
                       }
    
                        //Make sure the number entered falls within the limits of 1 & 12
                if (choice >= 1 && choice <= 12) //Enter code to write multiplication selected
                        {
                            //Loop to execute code and output statement
                            for (int i = 1; i <= 12; i++) {
                                System.out.println(choice + " * " + i + " = " + choice * i);
                            }
                         //If user enters an invalid number
                        } else {
                            System.out.println("Invalid number, please try again");
                }
    
                        break;      //End switch statement if user selects option 1
    //Code part 2 ....................................................................................................
                    case 2:         //Initialise option 2 if user inputs option 2
    
    
    
                        System.out.println("Select the times tables to practice");
    
                        //read in times table value choosen
                        choice = scanner.nextInt();
    
                        //Initialise times table loop value
                        int i = 0;
    
                        //Initialise code for correctAnswer
                        int correctAnswer = choice * i;
    
    
                        //Validate user input
                        if (choice >= 1 && choice <= 12) {
    
                            //Initialise loop for times table and out put questions
                            for (i = 1; i <= 12; i++) {
                                System.out.print(choice + " * " + i + " = ");
    
                                //read in times table value choosen
                                int answer = scanner.nextInt();
                                //Validate user input is correct
                                int exactAnswer = choice * i;
    
                                //Initialise code directly below if user inputs the correctAnswer
                                if (answer == exactAnswer) {
                                    System.out.println("Correct");
                                    correctCrt++;//If the user input is correct increment the correctCrt variable by 1
    
                                    //Initialise code directly below if the user input is incorrect
                                } else {
                                    System.out.println("Wrong : the answer is :" + exactAnswer);
                                }
    
                            }//Output the total amount for correct questions answered
                            System.out.println("Finished : number of correct answers: " + correctCrt);
    
                        }
                        break;      //End switch statement if user selects option 2
    //Code Part 3...................................................................................................
    
    
                    case 3:         //Initialise option 3 if user inputs option 3
    
                        //Execute code to generate random numbers
                        for (i = 1; i <= 12; i++) {
                            int randomNumber1 = 1 + ((int) (Math.random() * 12)); //get a new random number within the range of 1-12 for the first operand..
                            int randomNumber2 = 1 + ((int) (Math.random() * 12)); //get a new random number within the range of 1-12 for the second operand..
    
                            //Output random times table question on screen to user
                            System.out.print(randomNumber1 + " * " + randomNumber2 + " = ");
    
                            //Scan for user input (Answer)
                            int userAnswer = scanner.nextInt();
    
                            //Initialise variable for the correct answer from the randomly generated numbers
                            correctAnswer = randomNumber1 * randomNumber2;
    
                            //Initialise code directly below if user inputs the correctAnswer
                            if (userAnswer == correctAnswer) {
                                System.out.println("You are correct");
                                correctCrt++;//If the user input is correct increment the correctCrt variable by 1
    
                                //Initialise code directly below if the user input is incorrect
                            } else {
                                System.out.println("Wrong the answer is : " + correctAnswer);
                            }
                        }
                        //Output the total amount for correct questions answered
                        System.out.println("Finished : number of correct answers: " + correctCrt);
                        for (i = 0; i < correctCrt; i++) {
                        }
                        break;      //End switch statement if user selects option 3
                    case 4:
                        option = 4; //Initialise option 4 if user inputs option 4
                        //Output statement when user selects option 4
                        System.out.println("Thank you for playing bye...");
                        break;      //End program if user selects option 4
    
                    //Output statement if user enters invalid selection
                    default:
                        System.out.println("Please enter a valid option");
                }
            } //Exit program
            while (option != 4);
        }//Main Method
    }//Class Method
    Last edited by Martyn; 01-05-2012 at 07:01 PM.

  13. #13
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,882
    Rep Power
    25

    Default Re: Multiple try & catch statements within a switch

    Edit your post and wrap your code with[code]<YOUR CODE HERE>[/code] to preserve formatting.

    Did you add the debug code I suggested? What was printed out?

  14. #14
    Martyn is offline Member
    Join Date
    Nov 2011
    Location
    Belfast
    Posts
    37
    Rep Power
    0

    Default Re: Multiple try & catch statements within a switch

    Hi Norm.

    I think ive figured it out, but im not sure if this is good practice, I have to create a new scanner for each case of input see below.

    Java Code:
    Scanner keyboard = new Scanner (System.in);
    Is it good practice to create a scanner for each case within a switch?

    I have stripped the code back to one case until I figure out whats wrong with it.. A step in the right direction



    Java Code:
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    package testing;
    
    /**
     *
     * @author pc user
     */
    import java.util.Scanner;
    
    public class Testing {
    
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
    
    
            //Scan for user input
            Scanner scanner = new Scanner(System.in);
    
            // Variable that holds the option of the user...
            int option = 0;
            //Initialise variable for the amount of correctly answered questions
            int correctCrt = 0;
            int choice = 0;
            int userAnswer = 0;
            int randomNumber1 = 0;
            int randomNumber2 = 0;
    
            //Output options to user
            do {
                System.out.println("Multiplication tables game\n");
                System.out.println("1... Times tables - (select and view)");
                System.out.println("2... Practice - (select and practice)");
                System.out.println("3... New game - (12 random times table sums)");
                System.out.println("4... Quit");
    
                //read in the value choosen
                option = scanner.nextInt();
                //need to do this just after reading an int
                scanner.nextLine();
    
                //Initialise option selection
                switch (option) {
    
                    case 1://Initialise option 1 if user inputs option 1
    
                        Scanner keyboard = new Scanner (System.in);
    
                        //Output statement below once option 1 hase
                        System.out.println("Select times table to view (1 and 12 only)...");
    
                        try {
                            choice = keyboard.nextInt();
    
                        } catch (Exception ex) {
                            System.out.println("Invalid number, please try again 1 ");
                       }
    
                        //Make sure the number entered falls within the limits of 1 & 12
                if (choice >= 1 && choice <= 12) //Enter code to write multiplication selected
                        {
                            //Loop to execute code and output statement
                            for (int i = 1; i <= 12; i++) {
                                System.out.println(choice + " * " + i + " = " + choice * i);
                            }
                         //If user enters an invalid number
                        } else {
                            System.out.println("Invalid number, please try again 2");
                }
    
                        break;      //End program if user selects option 4
    
                    //Output statement if user enters invalid selection
                    default:
                        System.out.println("Please enter a valid option");
                }
            } //Exit program
            while (option != 4);
        }//Main Method
    }//Class Method
    Last edited by Martyn; 01-05-2012 at 07:54 PM.

  15. #15
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,882
    Rep Power
    25

    Default Re: Multiple try & catch statements within a switch

    how to get the program to stop printing both the catch & else statement.
    Can you show an example of what you are talking about?

    Remember the computer executes statements one after the other in sequence and as determined by different combinations of statements. If you don't want the execution flow to continue through statements, you need to add some statements to make it go where you want it to go.
    After a catch block is executed the next statement to be executed will be the one following the catch block.

  16. #16
    Martyn is offline Member
    Join Date
    Nov 2011
    Location
    Belfast
    Posts
    37
    Rep Power
    0

    Default Re: Multiple try & catch statements within a switch

    I have numbered the statements 1 & 2

    the catch is 1
    and
    the else is 2

    System.out.println("Invalid number, please try again 1 ")
    System.out.println("Invalid number, please try again 2 ")

    this is what prints

    run:
    Multiplication tables game

    1... Times tables - (select and view)
    2... Practice - (select and practice)
    3... New game - (12 random times table sums)
    4... Quit
    1
    Select times table to view (1 and 12 only)...
    marty
    Invalid number, please try again 1
    Invalid number, please try again 2

    Multiplication tables game

    1... Times tables - (select and view)
    2... Practice - (select and practice)
    3... New game - (12 random times table sums)
    4... Quit

  17. #17
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,882
    Rep Power
    25

    Default Re: Multiple try & catch statements within a switch

    Have you looked at your code to see what conditions must be true or false for the second line(Invalid number) to print?
    If you don't want that second line(Invalid number) to print you need to change the logic in the program (an if statement perhaps) so that the second line is not printed.

    Where do you want the execution to go after the first line(Invalid number) is printed?

  18. #18
    Martyn is offline Member
    Join Date
    Nov 2011
    Location
    Belfast
    Posts
    37
    Rep Power
    0

    Default Re: Multiple try & catch statements within a switch

    Thanks for that Norm ile try to insert a condition im thinking an if else (<1 || >12) as opposed to an else which covers everything

    I would like it to restart the game, rather than stop the program, take it back to the main menu

  19. #19
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,882
    Rep Power
    25

    Default Re: Multiple try & catch statements within a switch

    take it back to the main menu
    One way is to wrap the code in a loop, with the main menu at the top. To restart at the top, use the continue statement.

  20. #20
    Martyn is offline Member
    Join Date
    Nov 2011
    Location
    Belfast
    Posts
    37
    Rep Power
    0

    Default Re: Multiple try & catch statements within a switch

    Thanks again Norm,

    Martyn

Page 1 of 2 12 LastLast

Similar Threads

  1. switch statements & conditionals
    By linkxs in forum New To Java
    Replies: 7
    Last Post: 09-25-2011, 07:17 AM
  2. switch statements
    By jim01 in forum New To Java
    Replies: 7
    Last Post: 04-10-2011, 11:52 PM
  3. Using a switch/case with my if statements
    By coding in forum New To Java
    Replies: 2
    Last Post: 03-07-2011, 09:01 AM
  4. try and catch statements
    By vendetta in forum New To Java
    Replies: 4
    Last Post: 05-23-2010, 06:46 PM
  5. Replies: 2
    Last Post: 11-22-2008, 06:30 AM

Posting Permissions

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