0

I have a problem. If I assign a word to a string directly (by doing s="pass"), the code works the way I want. But if I try to assign it use a scanner, it seems to just skip over the if statement. I'm obviously new to java, could someone please try to help me?

import java.util.Scanner;

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

    String s;
    s=scan.next();

    if(s=="pass"){
        System.out.println("CORRECT");
    }
    else{
        System.out.println("INCORRECT");
    }
  }
}

I have imported the Scanner properly.

Waldi
  • 39,242
  • 6
  • 30
  • 78
alexdr3437
  • 61
  • 2
  • 8

3 Answers3

2

replace (s=="pass") with s.equals("pass") How do I compare strings in Java

Community
  • 1
  • 1
Josh Sobel
  • 1,268
  • 3
  • 14
  • 27
1

Here == will compare the references not the content.

To compare the content you need to use

.equals()    //If case is important

.equalsIgnorecase()  //If case is not important

But as your question says way to assign string is you can use = operator

PSR
  • 39,804
  • 41
  • 111
  • 151
0

The String.equals() method compares the contents of the string, whereas the == operator checks to see whether or not the objects are equal.

Change

if(s=="pass"){
        System.out.println("CORRECT");
    }

to

if(s.equals("pass")){
        System.out.println("CORRECT");
    }

More information: http://www.java-samples.com/showtutorial.php?tutorialid=221

anonymous
  • 1,111
  • 1
  • 10
  • 18