我正在从事剪刀石头布游戏项目,我想知道如何允许用户输入同一单词的多种类型。如果用户键入“ ROCK”,“ rock”或“ RoCk”,我希望程序允许它作为有效输入继续进行。另外,这是我自己的第一个项目,如果您有任何建议或批评,请告诉我。我想在编程方面变得更好,并乐意接受任何建议。谢谢。

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    //Displays what the game is
    System.out.println("Rock! Paper! Scissors!");

    String[] random = {"Rock", "Paper", "Scissors"};

    //Making the computer choice random
    String randomString = random[(int) (Math.random() * random.length)];

    //Telling the user to chose between rock paper and scissors
    System.out.println("Rock Paper or Scissors?");

    //User input
    String User;

    //If User doesn't enter Rock, Paper, or Scissors they will get an error message and have to try again
    do {
        User = input.nextLine();
        if (!User.equals("Rock") && !User.equals("Paper") && !User.equals("Scissors")) {
            System.out.println("ERROR Please enter \"Rock\" \"Paper\" or \"Scissors\" ");
        }
    } while (!User.equals("Rock") && !User.equals("Paper") && !User.equals("Scissors"));

    //Displays what the user chose
    if (User.equals("Rock")) {
        System.out.println("User has chosen: Rock!");
    }
    if (User.equals("Paper")) {
        System.out.println("User has chosen: Paper!");
    }
    if (User.equals("Scissors")) {
        System.out.println("User has chosen: Scissors!");
    }

    //Telling the user what the computer has chosen
    System.out.println("Computer has chosen: " + randomString + "!");

    //If the user's choice equals the computers choice the game is a tie
    if (User.equals("Rock") && randomString.equals("Rock")) {
        System.out.println("It is a tie!");
    }
    if (User.equals("Paper") && randomString.equals("Paper")) {
        System.out.println("It is a tie!");
    }
    if (User.equals("Scissors") && randomString.equals("Scissors")) {
        System.out.println("It is a tie!");
    }

    //Deciding who wins if both User and computer chose something different
    if (User.equals("Rock") && randomString.equals("Paper")) {
        System.out.println("Computer has won!");
    }
    if (User.equals("Rock") && randomString.equals("Scissors")) {
        System.out.println("User has won!");
    }
    if (User.equals("Paper") && randomString.equals("Scissors")) {
        System.out.println("Computer has won!");
    }
    if (User.equals("Paper") && randomString.equals("Rock")) {
        System.out.println("User has won!");
    }
    if (User.equals("Scissors") && randomString.equals("Paper")) {
        System.out.println("User has won!");
    }
    if (User.equals("Scissors") && randomString.equals("Rock")) {
        System.out.println("Computer has won!");
    }

}

最佳答案

String.equalsIgnoreCase(String str)满足您的需求。它将比较两个字符串而忽略大小写。

示例:对于您的情况,可以使用User.equalsIgnoreCase("Rock")

09-27 17:31