简体   繁体   中英

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.

Every time I use the Java suggested fixes like renaming inputChar, initializing the variable, or declaring it outside of the loop; the loop still executes even if I enter "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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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