java中的char问题

时间:2014-12-11 23:22:30

标签: java while-loop

我正在练习,我想创建一个带有无限循环while循环的代码,但我的问题是我不知道如何比较char或从键盘读取char。所以,到目前为止,我已经完成了以下代码,有什么建议吗?

    Scanner keyboard = new Scanner(System.in);
        System.out.println("Guess my favorite character: ");
        String letter = keyboard.nextLine();
        char secret = 'a';
        while (true) {
            System.out.println(" Enter guess:");
            String guess = keyboard.nextLine();
            for (int i = 0; i < guess.length(); i++) {

                if (guess.chartAt(i).equals('a')) {
                    break;

                }

            }
           System.out.println("YOU got it!"); 
        }

    }
}

3 个答案:

答案 0 :(得分:1)

break仅跳出for循环,因此您有一个无限while true循环。你可能想尝试这种方式。

    Scanner keyboard = new Scanner(System.in);
    System.out.println("Guess my favorite character: ");
    String letter = keyboard.nextLine();
    char secret = 'a';
    while (true) {
        System.out.println(" Enter guess:");
        String guess = keyboard.nextLine();
        for (int i = 0; i < guess.length(); i++) {
            if (guess.chartAt(i).equals('a')) {
                System.out.println("YOU got it!"); 
                return;
            }
        }
    }

答案 1 :(得分:0)

试试这个;

String secret = "a";
Boolean isFounded = false;
while (true) {
    System.out.println(" Enter guess:");
    String guess = keyboard.nextLine();
    for (int i = 0; i < guess.length(); i++) {
         if (guess.equals(secret)) {
              System.out.println("YOU got it!"); 
              isFounded = true;
         }
         if(isFounded) break;
     }
     if(isFounded) break;
}

答案 2 :(得分:0)

这里只有一个循环尝试一下。

  String secret = "a";
  String guess = "";
  Scanner keyboard = new Scanner(System.in);

  while(!guess.contains(secret)){
     System.out.println(" Enter guess:");
     guess = keyboard.nextLine();
  }
  System.out.println("YOU got it!");