0

I have a program in JAVA that I am working on. It uses recursion to count up based on the number entered. I'm using a while loop that loops if an error is thrown. I'm trying to code a feature that allows the user to continuously enter numbers until n/N is entered with a do/while loop. Here is my code so far:

public static void main(String[] args){
    Scanner keyboard = new Scanner(System.in);

    System.out.print("Enter a number: ");
    String input;
    input = keyboard.nextLine();        
    String again;
    do{
        while(true){
            try{
                int number = Integer.parseInt(input);
                int base = 1;
                /*
                  The countUp function is called from
                  from my parent class SimpleRecursion.java
                  which is where the recursion happens
                */
                countUp(base, number); 
                break;                
            }

            catch(NumberFormatException e){
                System.out.print("Error invalid entry." + "\n" + "Enter a number: ");
                input = keyboard.nextLine();
                continue;
            }
        }

        System.out.print("Again? y or n? ");
        again = keyboard.nextLine();
        if(again.equals("n") || again.equals("N"))
            System.exit(0);
    }while(again.equals("y") || again.equals("Y"));
}

However, when the try block breaks out of the while loop it seems to end the program. I've tried labeling my do loop A and the while loop B and using "break B", to break out of the while loop but that did not work either. Also: my Scanner import is at the top of the parent class. I can post the entire file, the code would work fine for a single correct input and the program loops correctly if the NumberFormatException is thrown. Thanks.

EDIT: I changed again=="string" to again.equals("string") and the results were the same.

The problem was in my countUp function which looked like this:

public static void countUp(int x, int end){
    if(x > end)
        System.exit(0); // When the number reaches the number entered. The 
                        // program ended. 
    else{
        System.out.print(x + "\n");
        countUp((x+1), end);
    }
}

0 Answers0