我创建了这个程序无限次地运行,要求用户输入一个选项(摇滚或纸张或剪刀),这似乎工作正常。问题是别的......如果或者......如果....满足。无论我给它输入什么,只需在else语句中输出else语句,(输入有效选项)。我无法发现我犯了如此错误的错误链接下面的代码.....提前感谢。
import java.util.Scanner;
import java.util.Random;
public class apples {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
Random number = new Random();
String rps[] = {"rock", "paper", "scissor"};
String player;
String ai;
int rand, pscore=0, aiscore=0;
while(1 < 2){
System.out.println("Take your pick \nrock \npaper \nscissor");
player = input.nextLine();
rand = number.nextInt(3);
ai = rps[rand];
System.out.println(ai);
if(player == ai){
pscore+=0;
aiscore+=0;
System.out.println("Your opponent chose " + ai + "\tYour score= "+ pscore + "\tOpponents score = "+aiscore);
System.out.print("\n");
continue;
}else{
if(player == "rock" && ai == "paper"){
aiscore+=1;
pscore+=0;
System.out.println("Your opponent chose " + ai + "\tYour score= "+ pscore + "\tOpponents score = "+aiscore);
System.out.print("\n");
continue;
}else if(player == "rock" && ai == "scissor"){
pscore+=1;
aiscore+=0;
System.out.println("Your opponent chose " + ai + "\tYour score= "+ pscore + "\tOpponents score = "+aiscore);
System.out.print("\n");
continue;
}else if(player == "paper" && ai == "rock"){
pscore+=1;
aiscore+=0;
System.out.println("Your opponent chose " + ai + "\tYour score= "+ pscore + "\tOpponents score = "+aiscore);
System.out.print("\n");
continue;
}else if(player == "paper" && ai == "scissor"){
aiscore+=1;
pscore+=0;
System.out.println("Your opponent chose " + ai + "\tYour score= "+ pscore + "\tOpponents score = "+aiscore);
System.out.print("\n");
continue;
}else if(player == "scissor" && ai == "rock"){
aiscore+=1;
pscore+=0;
System.out.println("Your opponent chose " + ai + "\tYour score= "+ pscore + "\tOpponents score = "+aiscore);
System.out.print("\n");
continue;
}else if(player == "scissor" && ai == "paper"){
aiscore+=0;
pscore+=1;
System.out.println("Your opponent chose " + ai + "\tYour score= "+ pscore + "\tOpponents score = "+aiscore);
System.out.print("\n");
continue;
}else{
System.out.println("Enter a valid choice");
System.out.print("\n");
continue;
}
}
}
}
}
答案 0 :(得分:0)
在java中,==
测试引用相等性:如果两个对象实际上是同一个对象。两个包含相同字符的字符串将无法通过此检查,这就是您的逻辑中发生的事情。
答案 1 :(得分:0)
而不是:
if(player == "rock" && ai == "paper"){
...
}
使用
if(player.equals("rock") && ai.equals("paper")){
...
}
这将适用于比较字符串的所有代码片段。