“不兼容的操作数类型int和字符串” [英] "Incompatible operand types int and string"

查看:1133
本文介绍了“不兼容的操作数类型int和字符串”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始学习代码(特别是Java),我正在测试一个密码系统,当你输入密码时,它变成变量password,它会检查它是否等于password2,即实际密码。这是代码:

I just started learning code (Java specifically), and i'm testing out a password system where when you type the password it becomes the variable "password" and it checks to see if it equals password2, the actual password. Here's the code:

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,使命召唤的密码;但问题是它不适用于字符串。这个问题的标题是出现的错误。有人可以帮助我吗?

I'm trying to check in the nested if statement whether the password I typed in matched password2, "Call of Duty"; but the problem is that it doesn't work with strings. The title of this question is the error that comes up. Can someone please help me?

推荐答案

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

when comparing strings you should use equals instead of == So use

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

这篇关于“不兼容的操作数类型int和字符串”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆