Search code examples
javamethodscallbackrestart

Unable to call back the name of the method I am while in it


I am making simple calculator program that initially and simply asks for a number in regards to addition, subtraction and division. If they enter a number that is not 1,2 or 3 I want to create an IOException and then recall the method to allow the user to be asked the same question again.

Maybe I'm missing something obvious. Any help appreciated. Thank you. ((Assume that scanner and all other functions are working))

public static void mathsChoice() throws IOException{ System.out.println("'1' for Addition, '2' for Subtraction, '3' for Division"); int resChoice = scanner.nextInt(); if (resChoice == 1){ additionMethod(); }else if (resChoice == 2){ subtractionMethod(); } else if (resChoice == 3){ divisionMethod(); }else { throw new IOException("Not valid, try again."); mathsChoice(); } }

The "mathsChoice();" within the else clause is causing the error: "Unreachable code"

mathsChoice();

Solution

  • It is telling you that mathsChoice() has no chance of execution ever. As in that particular block you are always throwing an exception which will terminate the program execution and the program will never reach this line mathsChoice()

    You should put the mathsChoice() call after the else block is closed.

    public static void mathsChoice() throws IOException{
            System.out.println("'1' for Addition, '2' for Subtraction, '3' for Division");
            int resChoice = scanner.nextInt();
            if (resChoice == 1){
                additionMethod();
            }else if (resChoice == 2){
                subtractionMethod();
            }   else if (resChoice == 3){
                divisionMethod();
            }else {
                  throw new IOException("Not valid, try again.");
            }
         mathsChoice();
    
    }