Daniel Bezden
Daniel Bezden

Reputation: 436

"Incompatible operand types int and string"

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."); 
            }   



    }   
}

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?

Upvotes: 0

Views: 41470

Answers (3)

Susam Pal
Susam Pal

Reputation: 34214

You have to make a couple of changes.

First password should be of type String since you want to store a string here and compare it with another string.

Next, just after age = test.nextInt();, you should do a test.nextLine() to consume the newline at the end of the input. We don't want to read this when we read the password.

Next, you should use password = test.nextLine(); to read the password entered by the user.

Lastly, you should compare it using: if (password.equals(password2)). == compares whether both the String objects have the same references, i.e., whether they are the same String objects as known to Java. You want .equals() here because it would compare whether the content of the two String objects are equal. In this case, password and password2 refer to two different String objects which may have the same content.

Upvotes: 1

John Snow
John Snow

Reputation: 5334

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

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

Upvotes: 4

Joachim Sauer
Joachim Sauer

Reputation: 308041

I try to give a hint instead of providing the full answer:

Check the data types of password and password2. Why are they different?

Upvotes: 10

Related Questions