当前位置: 首页 > 面试题库 >

“不兼容的操作数类型int和字符串”

史宸
2023-03-14
问题内容

我刚刚开始学习代码(特别是Java),并且我正在测试一个密码系统,在该密码系统中,键入密码时它将变为变量“
password”,并检查其是否等于实际密码password2。这是代码:

import java.util.Scanner;

public class LogicalOperators {
    public static void main(String args[]){

        Scanner test = new Scanner(System.in);
        int age;
        int password;
        String password2;
        password2 = "Call of Duty";

        System.out.println("Please enter your age:");
        age = test.nextInt();



            if (age >=18) { 
                System.out.println("You are old enough."); 
                System.out.println("Please enter the password:");
                password = test.nextInt();
                if (password == password2) {
                    System.out.println("Welcome back!");
                }else{
                    System.out.println("The password you typed was incorrect.");
                }

            }else{
                System.out.println("You are too young."); 
            }



    }   
}

我正在尝试检查嵌套的if语句,我输入的密码是否与password2“ Call of
Duty”匹配;但问题在于它不适用于字符串。该问题的标题是出现的错误。有人可以帮帮我吗?


问题答案:

比较字符串时,应使用equals代替==

if(password.equals(password2){
do something
}


 类似资料: