我是Java的新手,我试图用Eclipse编写一个程序,当用户键入'r'时,它将随机选择一把枪以“给”他们五把枪中的一把……类似于奥秘盒中的使命召唤僵尸。我对为什么输入“ r”后为什么不输出随机“ gun”感到困惑。请帮忙!!!
import java.util.Random;
import java.util.Scanner;
class apples{
public static void main(String[] args){
System.out.println("Type 'r' for a random gun");
Random dice = new Random();
int number;
Scanner input = new Scanner(System.in);
String userinput = input.nextLine();
if (userinput=="r"){
for (int counter=1; counter<=1; counter++){
number = 1+dice.nextInt(5);
if (number==1){
System.out.println("gun 1");
}else if (number==2){
System.out.println("gun 2");
}else if (number==3){
System.out.println("gun 3");
}else if (number==4){
System.out.println("gun 4");
}else if (number==5){
System.out.println("gun 5");
}
}
}else{
System.out.println(" ");
}
}
}
最佳答案
尝试使用
int randomInt = dice.nextInt(4);
if(userInput.equals("r")){
if (randomInt==1){
System.out.println("gun 1");
}else if (randomInt==2){
System.out.println("gun 2");
}else if (randomInt==3){
System.out.println("gun 3");
}else if (randomInt==4){
System.out.println("gun 4");
}else if (randomInt==5){
System.out.println("gun 5");
}
}
所以总体的最终代码应该像
public class test {
public static void main(String[] args) {
System.out.println("Type 'r' for a random gun");
Random dice = new Random();
int number;
Scanner input = new Scanner(System.in);
String userinput = input.nextLine();
int randomInt = dice.nextInt(4);
if (userinput.equals("r")) {
if (randomInt == 1) {
System.out.println("gun 1");
} else if (randomInt == 2) {
System.out.println("gun 2");
} else if (randomInt == 3) {
System.out.println("gun 3");
} else if (randomInt == 4) {
System.out.println("gun 4");
} else if (randomInt == 5) {
System.out.println("gun 5");
}
}
}
}