Skip to content
Advertisement

Trying to stop a Do-While Loop for an application

I’m creating an application for a homework, the problem is that I am trying to create a do-while loop to exit the application (Using the question “Do you want to exit (Y/N)”). To work with the do-while loop, I created a method to store the app and then called the method in the do-while loop, so that when I try to stop the loop, the method loops once more. I want when I type “Y” to the console the whole program stops and doesn’t loop one more time.

I created a simple example to explain my problem.

Here’s the method:

    public static void App(){
    Scanner sc = new Scanner(System.in);
    
    System.out.print("Write a number: ");
    int num1 = sc.nextInt();
    System.out.print("Write another number: ");
    int num2 = sc.nextInt();
    
    System.out.println("nResult: "+(num1+num2));
}  

And here I’m trying to create the loop in the main method:

    public static void main(String[] args) {
    
    Scanner sc2 = new Scanner(System.in);      
    App();
  
    String answer;
    do {
     System.out.println("Do you want to exit (Y/N)?");
     answer = sc2.next();
     App();
    } while (answer.equalsIgnoreCase("N")) ;
}

Advertisement

Answer

the problem is that I am trying to create a do-while loop to exit the application

You already have that in your program.

so that when I try to stop the loop, the method loops once more…

That doesn’t fit the goal of your program.

I want when I type “Y” to the console the whole program stops and doesn’t loop one more time

A lot of context that doesn’t fit right in.

But anyway, you just have to reorganize your program.

In other words, just move your App() method.

public static void main(String[] args) {
    
    Scanner sc2 = new Scanner(System.in);      
  
    String answer;
    do {
     App();
     System.out.println("Do you want to exit (Y/N)?");
     answer = sc2.next();
    } while (answer.equalsIgnoreCase("N")) ;
}

Also, I spotted a lot of bad practices, so I kind of fixed them:

public static void main(String[] args) throws Exception {
    try(Scanner sc2 = new Scanner(System.in)){
        String answer;
        do {
            App();
            System.out.print("Do you want to exit (Y/N)?");
            answer = sc2.nextLine();
        } while (answer.equalsIgnoreCase("N")) ;
    }
}

Lastly, maybe (just maybe) try to solve your problem first before seeking help for your homework.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement