输入不等于字符串

the input won't equal to the string

如您所见,我是 java 的新手。但我正在尝试制作剪刀石头布游戏。 但是当我将输入传递给方法时,它不是 return true,而输入是 "rock"。我检查了。

应该发生的是,当输入为 rock 时,true 得到 returned。现在它 return 是假的。

提前致谢!

import java.util.Scanner;

public class Game{

    static Boolean validInput(String input){
        if("rock" == input){
            return true;
        }
        else{
            return false;
        }
    }

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

        String choice;
        choice = input.nextLine();

        if(validInput(choice)){
            System.out.println(choice + " is valid input");
        }else{
            System.out.println(choice + " is not valid...");
        }

    }

}

在java中,如果你想比较字符串你必须使用.equals() 而不是== 所以你会

input.equals("rock")

这篇文章会给你更深入的解释:)
https://www.geeksforgeeks.org/difference-equals-method-java/

这个 post 可能也有帮助 How do I compare strings in Java?