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

Trying to stop a Do-While Loop for an application

提问人:Diret 提问时间:7/17/2022 最后编辑:Marco BonelliDiret 更新时间:7/19/2022 访问量:256

问:

我正在为家庭作业创建一个应用程序,问题是我正在尝试创建一个 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")) ;
}
Java 循环 方法 java.util.scanner do-while

评论

0赞 Utkarsh Sahu 8/17/2022
answer.equalsIgnoreCase("N")实际上意味着如果按下“N”,这个循环将继续。相反,您应该在此处写“Y”。

答:

0赞 Moraban 7/17/2022 #1

键入后程序再次运行的原因是,该方法是在循环部分内提出问题后运行的。nApp()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()

0赞 JumperBot_ 7/17/2022 #2

问题是我正在尝试创建一个 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")) ;
    }
}

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

0赞 Pradeep Kumar 7/17/2022 #3

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

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

}

0赞 DevilsHnd - 退した 7/17/2022 #4

这是另一种方法,只不过它使用循环而不是循环。提供了两种不同的方法,并且都提供用户条目验证:whiledo/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));
}