-1

可能重复:
如何比较 Java 中的字符串?

我写了一个程序,它会“掷骰子”并告诉你需要多少转才能获得 yahtzee。这可行,但是当它要求您再次访问时会出现问题。它会一直给我一个“无效的输入”,而实际上我输入的东西应该退出循环。这是我的代码,循环从第 24-34 行开始,但我会把它全部放好,以防万一早先出现问题。

import java.util.Scanner;
import java.util.Random;

public class Yahtzee {

public static void main(String[] args){

    int d[] = {0,0,0,0,0};
    int x = 0;
    Scanner s = new Scanner(System.in);
    Random r = new Random();

    while (1!=0){
        d[0] = r.nextInt(6);
        d[1] = r.nextInt(6);
        d[2] = r.nextInt(6);
        d[3] = r.nextInt(6);
        d[4] = r.nextInt(6);
        x+=1;

        if (d[0]==d[1] && d[0]==d[2] && d[0]==d[3] && d[0]==d[4]) {
            System.out.println("You got yahtzee, every dice showed " + Integer.toString(d[0]));
            System.out.println("It only took " + Integer.toString(x) + " turns");
            while (1!=3) {
                System.out.print("Go again? y/n: ");
                String ans = s.nextLine();
                if (ans.toLowerCase()=="n"){
                    System.exit(0);
                } else if (ans.toLowerCase()=="y") {
                    break;
                } else {
                    System.out.println("Invalid input!");
                }
            }

        }   
    }   
}   
}

老实说,我无法弄清楚这一点,尽管它可能非常明显。问题出在哪里?

4

3 回答 3

3

用于.equals比较字符串,而不是相等运算符==

if (ans.toLowerCase().equals("n")){
    System.exit(0);
} else if (ans.toLowerCase().equals("y")) {

相等运算符仅检查它们的内存位置是否相等,在这种情况下并非如此。

于 2012-10-04T00:32:21.873 回答
1

用于String.equals检查字符串内容。该==运算符依赖于引用相等,因此前 2 个 if 语句表达式永远不会是true. 你可以有:

if (ans.toLowerCase().equals("n")) {
   System.exit(0);
} else if (ans.toLowerCase().equals("y")) {
   break;
} else {
   System.out.println("Invalid input!");
}
于 2012-10-04T00:31:27.130 回答
0

前面两个答案都是正确的,你必须使用 String 类的 .equals 方法。

程序中的 == 运算符实际上是比较 2 个字符串对象引用而不是字符串的内容。

对于刚开始使用 Java 的人来说,这是一个很常见的错误。

有关更多信息,请参见此处:http ://www.java-samples.com/showtutorial.php?tutorialid=221

于 2012-10-04T00:39:49.687 回答