【问题标题】:Using char instead of an String for end a do while loop. It's possible? Java使用 char 而不是 String 来结束 do while 循环。这是可能的?爪哇
【发布时间】:2017-11-05 21:32:30
【问题描述】:

所以在这段代码中,布尔值是用户的输入,但它只需要一个输入。如果用户按 [c],则 do while 继续,但如果按任何其他键则停止。我已经有了与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") );

也许它已经意识到我试图找到一个答案......也许我是少年。但我不知道我该怎么做。 (如果已经重复请告诉我不要取消投票)

【问题讨论】:

    标签: java string char


    【解决方案1】:

    如果您想使用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(...) 方法以仅使用一个字符。

    【讨论】:

      【解决方案2】:

      是的,这是可能的,非常接近。您需要使用 String.equals 或 String.equalsIgnoreCase 而不是您尝试的比较字符串。参考How do I compare strings in 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');
      }
      

      【讨论】:

      • 我想使用char 而不是String
      • 答案就在其中,抱歉我错过了那部分。
      • 好吧,但现在的想法是,如果用户输入 C ?它会重新开始。
      • 由于 chr != 'c' 条件,只需将其更改为 chr == 'c'
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-16
      • 1970-01-01
      • 1970-01-01
      • 2018-04-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多