繁体   English   中英

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

[英]Trying to stop a Do-While Loop for an application

我正在为作业创建一个应用程序,问题是我正在尝试创建一个 do-while 循环来退出应用程序(使用问题“你想退出(Y/N)”)。 为了使用 do-while 循环,我创建了一个方法来存储应用程序,然后在 do-while 循环中调用该方法,这样当我尝试停止循环时,该方法会再次循环。 我希望当我在控制台上输入“Y”时整个程序停止并且不再循环一次。 感谢您的阅读。

我创建了一个简单的示例来解释我的问题。

这是方法:

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

在这里,我试图在 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")) ;
}

键入n后程序再次运行的原因是App()方法是在循环的do部分中询问问题后运行的。

下面的代码是我能想到的最简单的解决方法。

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

附带说明一下,Java 中的方法在遵循典型的 Java 命名约定时应该是小写的。 虽然这不会影响您的代码运行方式,但我建议将方法从App()重命名为app()

问题是我正在尝试创建一个 do-while 循环来退出应用程序

你的程序中已经有了它。

这样当我尝试停止循环时,该方法会再次循环...

这不符合您程序的目标。

我希望当我在控制台输入“Y”时整个程序停止并且不再循环一次

很多不适合的上下文。

但无论如何,你只需要重新组织你的程序。

换句话说,只需移动您的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")) ;
}

另外,我发现了很多不好的做法,所以我修复了它们:

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

最后,也许(只是也许)在为你的作业寻求帮助之前先尝试解决你的问题。

您的代码中的一切看起来都不错,只需更改代码块中所示的执行逻辑即可。

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

}

这是另一种方法,除了它使用while循环而不是do/while循环。 提供了两种不同的方法,并且都提供用户输入验证:

方法#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));
}

方法#2:

下一种方法使用Scanner#nextLine()方法。 关于nextLine()要记住的是,如果您在控制台应用程序中使用它,那么基本上建议您将它用于所有内容(所有提示)。 此版本还提供“退出”机制。 阅读代码中的注释:

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