应用字符串并在java中的if-else语句中使用它们

时间:2014-11-24 01:52:44

标签: java string if-statement

每当我运行这个程序时,一切都运行良好,直到我到达底部,我应该键入“y”或“n”。我输入“n”(没有括号),由于某种原因它继续循环。最有可能的是,我使用不当。但是,任何帮助都完全赞赏!谢谢!

  import java.util.Scanner;

  public class GuessTheNumberEC
{
   public static void main(String[] args)
   {

  Scanner reader = new Scanner(System.in);
  int guess = 5;
  int randomNumber;
  int guessRepetition = 1;
  String yes = "y";
  String no = "n";
  String answer;

  randomNumber = (int)(Math.random() * 24 + 1);
  System.out.println(randomNumber);

  for(;;){

     for (int x = 1; x<=4; x++) {
        System.out.println("Guess a number from 1 - 25.");
        guess = reader.nextInt();

        if(guess == randomNumber) {
           System.out.println("Guess #" + guessRepetition + " is correct.");

           if(guessRepetition == 1) {
              System.out.println("Great, you guessed the number in " + guessRepetition + " try.");
              break;
           }
           else {
              System.out.println("Great, you guessed the number in " + guessRepetition + " tries.");
              break;
           }
        }  
        else if (guess > randomNumber) {
           System.out.println("Guess # " + guessRepetition + " is too high.");
           guessRepetition ++;


        } 
        else if (guess < randomNumber) {
           System.out.println("Guess # " + guessRepetition + " is too low.");
           guessRepetition ++;

        }
     }

     if (guess != randomNumber) 
     {
        System.out.println("The number was " + randomNumber + ".");
        System.out.println("You couldn't guess the number in 4 tries, so you lose.");
     }
     System.out.println("Would you like to play again? Press 'y' or 'n'");
     answer = reader.next();

     if (answer == no)
        break;
  }

} }

2 个答案:

答案 0 :(得分:0)

更改

answer == no

answer.equals(no)

为什么呢?因为==运算符将比较参考级别的两个变量。你的字符串&#34;回答&#34;将包含与字符串相同的字符&#34; no&#34;但它们是不同的对象,因此==将返回false。 equals()将测试两个字符串的内容,如果它们包含完全相同的字符(区分大小写),则返回true。

答案 1 :(得分:0)

了解==.equals之间的区别。

==在原始值或对象引用之间进行比较,如果对象引用相同,则它们将相等。

.equals比较对象的内容,这就是你在这种情况下应该使用的内容。