这只是一个简单的剪刀石头布游戏,我用eclipse做为测试,我已经较早地通过这个网站进行了测试,并得到了一些答案,但是现在我遇到了一个找不到胜利者的问题?

package rockPaperScissors;

import java.util.Scanner;
import java.util.Random;

public class RockPaperScissors {

    public static void main(String args[]) {
        String playerChose;
        String computerChose;
        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();

            if (playerChose.equals("rock") && computerChose.equals("scissors") || playerChose.equals("paper") && computerChose.equals("rock") || playerChose.equals("scissors") && computerChose.equals("paper")) {
                System.out.println("Player won!");
            }
            if(playerChose.equals(computerChose)) {
                System.out.println("Game tied!");
            }
            if(computerChose.equals("rock") && playerChose.equals("scissors") || computerChose.equals("paper") && playerChose.equals("rock") || computerChose.equals("scissors") && computerChose.equals("paper")) {
                System.out.println("Computer won!");
            }
        }
    }
}

最佳答案

经过测试和工作

立即初始化computerChose,因此更改
String computerChose;String computerChose = "";

并删除行computerChose = new String();,因为在开关盒中初始化computerChoose字符串后将其设置为空字符串。

关于java - Java-为什么不起作用?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20169746/

10-09 09:40