所以我一直在youtube上观看一些“thenewboston”,我刚刚开始学习java一小时前,我似乎无法找到我的问题。 (没有错误消息)
package rockPaperScissors;
import java.util.Scanner;
import java.util.Random;
public class RockPaperScissors {
public static void main(String args[]){
String playerChose;
String computerChose;
String winner;
while(true){
System.out.println("Welcome to rock paper scissors!");
System.out.println("Please enter \"rock\", \"paper\", or \"scissors\"");
Scanner playerChoice = new Scanner (System.in);
playerChose = playerChoice.nextLine();
Random computerChoice = new Random();
int computer = computerChoice.nextInt(3) + 1;
switch(computer){
case 1:
computerChose = "rock";
System.out.println("Computer chose rock!");
break;
case 2:
computerChose = "paper";
System.out.println("Computer chose paper!");
break;
case 3:
computerChose = "scissors";
System.out.println("Computer chose scissors!");
}
computerChose = new String();
winner = new String();
if(playerChose=="rock" && computerChose=="scissors" || playerChose=="paper" && computerChose=="rock" || playerChose=="scissors" && computerChose=="paper"){
winner="player";
}
if(playerChose==computerChose){
winner="NoWinner";
}
if(computerChose=="rock" && playerChose=="scissors" || computerChose=="paper" && playerChose=="rock" || computerChose=="scissors" && playerChose=="paper"){
winner="computer";
}
if(winner!="NoWinner"){
System.out.println(winner+" won!");
}else{
System.out.println("Game tied!");
}
}
}
}
是的,我是这个java的新手,我不知道为什么这个代码不起作用,因为我认为它确实会起作用。我敢肯定,这只是我需要学习的愚蠢行为。由于我来自Python,因此对于Java中存在很多Python中不存在的规则来说这要复杂得多。
答案 0 :(得分:2)
要比较字符串,而不是==
,您必须使用equals()
方法:
str1.equals(str2)
当您使用==
时,您正在比较内存引用,因为String
不是Java中的原始数据类型。尝试在Google上搜索它。