0

我对java比较陌生,我正在尝试在Eclipse中编写一个程序,当用户输入'r'时,它会随机选择一把枪来“给”他们五支枪中的一支......有点像神秘盒子使命召唤僵尸。我很困惑为什么在我输入“r”后它不会输出随机的“枪”。请帮忙!!!

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(" ");
    }

}
}
4

2 回答 2

1

尝试使用

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");
        }
    }

}

}

于 2013-08-27T02:01:16.550 回答
0
于 2013-08-27T02:21:26.207 回答