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

时间:2011-07-26 09:04:04

标签: java string if-statement int

我刚开始学习代码(特别是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语句是否输入了匹配密码2的密码,“使命召唤”;但问题是它不适用于字符串。这个问题的标题是出现的错误。有人可以帮助我吗?

3 个答案:

答案 0 :(得分:9)

我尝试提示而不是提供完整的答案:

检查passwordpassword2的数据类型。他们为什么不同?

答案 1 :(得分:3)

比较字符串时,应使用equals而不是== 所以使用

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

答案 2 :(得分:1)

你必须做出一些改变。

首先password应该是String类型,因为您要在此处存储字符串并将其与另一个字符串进行比较。

接下来,在age = test.nextInt();之后,您应该在输入结束时使用test.nextLine()来使用换行符。我们在阅读密码时不想阅读此内容。

接下来,您应该使用password = test.nextLine();来读取用户输入的密码。

最后,您应该使用以下代码进行比较:if (password.equals(password2))==比较两个String对象是否具有相同的引用,即它们是否与Java已知的String对象相同。你想在这里.equals()因为它会比较两个String对象的内容是否相等。在这种情况下,passwordpassword2引用两个可能具有相同内容的不同String对象。

相关问题