简体   繁体   English

尝试停止应用程序的 Do-While 循环

[英]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)").我正在为作业创建一个应用程序,问题是我正在尝试创建一个 do-while 循环来退出应用程序(使用问题“你想退出(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.为了使用 do-while 循环,我创建了一个方法来存储应用程序,然后在 do-while 循环中调用该方法,这样当我尝试停止循环时,该方法会再次循环。 I want when I type "Y" to the console the whole program stops and doesn't loop one more time.我希望当我在控制台上输入“Y”时整个程序停止并且不再循环一次。 Thank you for reading.感谢您的阅读。

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:在这里,我试图在 main 方法中创建循环:

    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")) ;
}

The reason why your program is running again after you type n is because the App() method is ran after the question is asked within the do part of the loop.键入n后程序再次运行的原因是App()方法是在循环的do部分中询问问题后运行的。

This code below is the simplest fix I could think of.下面的代码是我能想到的最简单的解决方法。

public static void main(String[] args) {
    Scanner sc2 = new Scanner(System.in);
    // I removed the line 'App();' as the App method will always run at least one time. Therefore putting that method within the 'do' part of the loop allows us to ask the user if they wish to exit or not after they have received their answer.
    String answer;
    do {
        App();
        System.out.print("Do you want to exit (Y/N)?"); //I changed the 'println' to 'print' here
        answer = sc2.next();
    } while (answer.equalsIgnoreCase("N")) ;
}

As a side note, methods in java should be lower-case when following typical Java naming conventions.附带说明一下,Java 中的方法在遵循典型的 Java 命名约定时应该是小写的。 While this will not affect how your code runs, I would suggest renaming the method from App() to app() .虽然这不会影响您的代码运行方式,但我建议将方法从App()重命名为app()

the problem is that I am trying to create a do-while loop to exit the application问题是我正在尝试创建一个 do-while 循环来退出应用程序

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我希望当我在控制台输入“Y”时整个程序停止并且不再循环一次

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.换句话说,只需移动您的App()方法。

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.最后,也许(只是也许)在为你的作业寻求帮助之前先尝试解决你的问题。

Everything looks good in your code, Just change the execution logic as shown in code blocks.您的代码中的一切看起来都不错,只需更改代码块中所示的执行逻辑即可。

public static void main(String[] args) {
Scanner sc2 = new Scanner(System.in);      
App();   //remove this line from here

String answer;
do {
 App();  //call App function here so that it got executed at least one time 
 System.out.println("Do you want to exit (Y/N)?");
 answer = sc2.next();
 App();   //remove this as well
} while (answer.equalsIgnoreCase("N")) ;

} }

Here is yet another approach except it uses a while loops instead of do/while loops.这是另一种方法,除了它使用while循环而不是do/while循环。 Two different approaches are provided and both provide User entry validation:提供了两种不同的方法,并且都提供用户输入验证:

Approach #1:方法#1:

public static void appMethod() {
    Scanner sc = new Scanner(System.in);
    
    int num1 = Integer.MIN_VALUE;    // Initialize with some obscure value.
    int num2 = Integer.MIN_VALUE;    // Initialize with some obscure value.
    
    while (num1 == Integer.MIN_VALUE) {
        System.out.print("Write a number: ");
        try {
            num1 = sc.nextInt();
        } catch ( java.util.InputMismatchException ex) { 
            System.out.println("Invalid Entry! Try again..." 
                               + System.lineSeparator());
            sc.nextLine(); // consume the ENTER key hit otherwise this error will keep cycling.
            num1 = Integer.MIN_VALUE;
        }
    }
    while (num2 == Integer.MIN_VALUE) {
        System.out.print("Now, write yet another number: ");
        try {
            num2 = sc.nextInt();
        } catch ( java.util.InputMismatchException ex) { 
            System.out.println("Invalid Entry! Try again..." 
                               + System.lineSeparator());
            sc.nextLine(); // consume the ENTER key hit otherwise this error will keep cycling.
            num2 = Integer.MIN_VALUE;
        }
    }
    
    System.out.println("\nResult: " + num1 +" + " + num2 + " = " + (num1 + num2));
}

Approach #2:方法#2:

This next approach makes use of the Scanner#nextLine() method.下一种方法使用Scanner#nextLine()方法。 The thing to remember about nextLine() is that, if you use it in your console application then basically recommend you use it for everything (all prompts).关于nextLine()要记住的是,如果您在控制台应用程序中使用它,那么基本上建议您将它用于所有内容(所有提示)。 A 'quit' mechanism is also available in this version.此版本还提供“退出”机制。 Read the comments in code:阅读代码中的注释:

public static void appMethod() {
    Scanner sc = new Scanner(System.in);
    
    // Retrieve first number...
    String num1 = "";
    while (num1.isEmpty()) {
        System.out.print("Write a number (q to quit): ");
        // Making use of the Scanner#nextLine() method
        num1 = sc.nextLine();
        // Has 'q' been supplied to Quit?
        if (num1.equalsIgnoreCase("q")) {
            return;
        }
        /* Validate the fact that a signed or unsigned Integer or 
           Floating Point value has been entered. If not show Msg. */
        if (!num1.matches("-?\\d+(\\.\\d+)?")) { 
            System.out.println("Invalid Entry! (" + num1 + ") Try again..." 
                               + System.lineSeparator());
            num1 = "";  // empty num1 so as to re-loop.
        }
    }
    
    // Retrieve second number...
    String num2 = "";
    while (num2.isEmpty()) {
        System.out.print("Now, write yet another number (q to quit): ");
        num2 = sc.nextLine();
        if (num2.equalsIgnoreCase("q")) {
            return;
        }
        if (!num2.matches("-?\\d+(\\.\\d+)?")) { 
            System.out.println("Invalid Entry! (" + num2 + ") Try again..." 
                               + System.lineSeparator());
            num2 = "";
        }
    }
    
    // Convert the numerical strings to double data type values.
    double number1 = Double.parseDouble(num1);
    double number2 = Double.parseDouble(num2);
    
    // Display the result.
    System.out.println("\nResult: " + num1 +" + " + num2 + " = " + (number1 + number2));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM