我是一名新的程序员,并试图通过随机项目来教自己Java。下面是一个“Rock,Paper,Scissors”游戏,我面临的问题是在打印“a”之后,程序结束并且不会继续下面的if else语句。我们将非常感谢您提供的任何帮助。
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("Hello & Welcome to Rock, Paper, Scissors. What's your name?");
Scanner scan = new Scanner(System.in);
String userChoice = scan.nextLine();
System.out.println("Hello, " + userChoice + ". Let's start a game!");
Scanner scan = new Scanner(System.in);
System.out.println("Choose one: Rock, Paper, Scissors");
String userFirstChoice = scan.nextLine();
System.out.println("You chose " + userFirstChoice);
double a = Math.random();
System.out.println(a);
if (a >= 0.00 && a<= 0.3){
if ( userFirstChoice== "Rock"){
System.out.println("Rock vs Rock: TIE");
}
else if (userFirstChoice == "Paper"){
System.out.println("Rock vs Paper: YOU LOSE!");
}
else if (userFirstChoice == "Scissors"){
System.out.println("Rock vs Scissors: YOU WIN!");
}
}
else if (a>=0.3 && a<=0.6){
if(userFirstChoice == "Paper"){
System.out.println("Paper vs Paper: TIE!");
}
else if (userFirstChoice == "Rock"){
System.out.println("Rock vs Paper: YOU LOSE!");
}
else if(userFirstChoice == "Scissors"){
System.out.println("Scissors vs Paper: YOU WIN!");
}
}
else if (userFirstChoice == "Scissors"){
System.out.println("Scissors vs Scissors: TIE!");
}
else if (userFirstChoice == "Paper"){
System.out.println("Paper vs Scissors: YOU LOSE!");
}
else if (userFirstChoice == "Rock") {
System.out.println("Rock vs Scissors: YOU WIN!");
}
}
}
答案 0 :(得分:2)
您无法使用==
来比较Java中的字符串。 (==
比较引用,而==
的操作数可能是对不同字符串的引用,即使字符串 contents 相同。)
请改用userFirstChoice.equals("Scissors")
等。
您对double
类型上的关系运算符的使用是正确的。