简体   繁体   English

即使条件为假,Do-while 循环也会执行

[英]Do-while loop executing even though condition is false

I need to implement both methods in this code using a do-while loop in the main method.我需要在 main 方法中使用 do-while 循环在此代码中实现这两种方法。

Every time I use the Java suggested fixes like renaming inputChar, initializing the variable, or declaring it outside of the loop;每次我使用 Java 时都会建议修复,例如重命名 inputChar、初始化变量或在循环外声明它; the loop still executes even if I enter "E".即使我输入“E”,循环仍然会执行。 Any help would be greatly appreciated.任何帮助将不胜感激。

import java.util.Scanner;
public class Practice {
    
    static Scanner scanner = new Scanner(System.in);
    
    public static void main(String[] args) {
        
        
        do {
            char inputChar = getInputCharFromUser();
            String value = getValueFromChar(inputChar);
            System.out.println(value);

        } while (inputChar != ('E'));
        scanner.close();

    }
    public static char getInputCharFromUser() {
        final String CHAR_PROMPT = "Enter input char: ";
        System.out.println(CHAR_PROMPT);
        char inputChar = scanner.nextLine().charAt(0);
        return inputChar;

    }
    public static String getValueFromChar(char inputChar) {

        switch (inputChar)

        {

        case 'P':
            return "Player";
        case 'p':
            return "Player";
        case 'X':
            return "Wall";
        case 'x':
            return "Wall";
        case ' ':
            return "Empty";
        default:
            return "Invalid";

        }
    }
}

Try to use a while-loop instead of do-while-loop, you can still add an if-condition or everything else in the while-loop, so it doesnt matter.尝试使用 while 循环而不是 do-while 循环,您仍然可以在 while 循环中添加 if 条件或其他所有内容,所以没关系。

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

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