使用 char 而不是字符串来结束 do while 循环。有可能?爪哇岛



所以在这个 do while 代码中,布尔值是用户的输入,但它只需要一个输入。如果用户按 [c],则在继续时执行,但如果按任何其他键将停止。我已经有了与String c = "";有关的代码,但我想用char完成.当我使用char c [];无法使用c = kb.next().toUpperCase();时,也会发生另一个问题

这是我所做的示例代码。

Scanner kb = new Scanner(System.in);
String c = "";
do {
     //some code.
     //here asks to the user to continue or not.
     System.out.println("Press [c] to continue, any key to exit.");
     c = kb.next().toUpperCase();
} while ( c.equals == ("C") );

也许我已经很惊讶了,我试图找到答案......也许我是小时候。但我想知道我该怎么做。(如果它已经重复,请告诉我不要取消投票)

如果你想使用char c而不是String c,这个代码:

char c;
do {
     System.out.println("Press [c] to continue, any key to exit.");
     c = kb.next(".").toUpperCase().charAt(0);
} while (c == 'C');

这个想法是将"."传递给next(...)方法以仅使用一个字符。

是的,这是可能的,非常接近。您需要使用 String.equals 或 String.equalsIgnoreCase 来比较字符串,而不是您尝试的内容。请参阅如何在 Java 中比较字符串?

public static void main(String[] args) {
    Scanner kb = new Scanner(System.in);
    String c = "";
    do {
        //some code.
        //here asks to the user to continue or not.
        System.out.println("Press [c] to continue, any key to exit.");
        c = kb.next().toUpperCase();
    } while (!c.equalsIgnoreCase("C"));
}

带字符

public static void main(String[] args) {
    Scanner kb = new Scanner(System.in);
    char chr;
    do {
        //some code.
        //here asks to the user to continue or not.
        System.out.println("Press [c] to continue, any key to exit.");
        chr = kb.next().toCharArray()[0];
    } while (chr != 'c');
}

最新更新