我写了一个游戏代码,给您一个单词来拼写。但是即使写了正确的单词,也没有得到“您赢了”的信息。我得到的只是“错误答案”。请找出错误并提出改进方法。
import java.util.*;
public class game {
public static void main(String args[]){
Scanner input=new Scanner(System.in);
Random rand=new Random();
//THE WORD DIRECTORY
String[][] list=new String[][]{
{"google","a search engine"},
{"facebook","a social networking site"},
{"java", "this language"},
};
//CHOOSING THRE WORD
int n=rand.nextInt(3);
String theword=list[n][0];
String thehint=list[n][1];
//JUMBLING THE WORD
String jumbledword=theword;
char a[] = jumbledword.toCharArray();
for(int i=0;i<jumbledword.length();i++){
int input1=rand.nextInt(jumbledword.length());
int input2=rand.nextInt(jumbledword.length());
char temp=a[input1];
a[input1]=a[input2];
a[input2]=temp;
}
//THE GAME
System.out.println("\t\tWELCOME TO JUMBLE WORD");
System.out.println("1.Unscrabble the given word");
System.out.println("2.Press 'hint'for hint");
System.out.println("3.Press 'quit' to quit");
System.out.print("The word:" );
System.out.println(a);
String guess;
do{ guess=input.nextLine();
if(guess==theword){
System.out.println("YOU WIN");
}
else if(guess=="hint"){
System.out.println(thehint);
}
else if(guess=="quit"){
System.out.println("Better luck next time. The answer is :");
System.out.println(theword);
}
else{
System.out.println("Wrong answer .Try again");
}
}while(!guess.equals("quit")&&!guess.equals(theword));
}}
欢迎任何建议。
最佳答案
==运算符用于检查对象是否相等,而不是值。您想改用equals方法。
代替
if(guess==theword){
使用
if(guess.equals(theword)){
为了进一步阐述,假设您有三个字符串:
String s1 = new String("abc");
String s2 = s1;
String s3 = new String("abc");
在这种情况下,将发生以下结果:
s1.equals(s2); // true, same value
s1 == s2; // true, same object
s1.equals(s3); // true, same value
s1 == s3; // false, different objects
关于java - 程序未按预期运行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28852664/