-3
import java.util.Scanner;
import java.util.Random;



public class cominback{
    public static void main(String args[]){
      Scanner key = new Scanner(System.in);
      System.out.println(" please enter a password:");
      String x = key.nextLine();
      System.out.println("Connfirm your password:");
      String y = key.nextLine();
      if ( x == null)
          System.out.println("please restart the program:");
      if (x != y)
          System.out.println("wrong password");
      if (x == y )
          System.out.println("you are logged in");

    }
}

It always print out wrong password for even when the input is same passwords. how can i fix this problem? did i do something wrong or is it my eclipse glitching?

Razib
  • 10,965
  • 11
  • 53
  • 80

2 Answers2

1

You should use equals method to compare two string like:

if (x.equals(y))//password matches
SMA
  • 36,381
  • 8
  • 49
  • 73
0

The == check against reference. Use equals() instead for checking if tow string are meaningfully equals. Use the following code snippet - f

if( x.equals(y) ){}
if( !(x.equals(y)) ){}

Note:

String str1 = "string one";
String str2 = str1;
String str3 = "string two";

System.out.println( str1.equals(str3) ); //false; meaningfully not equals.
System.out.println( str1 == str2 ); //true; referencing same String content
System.out.println( "string one".equals(str1) ); //true; meaningfully equals
Razib
  • 10,965
  • 11
  • 53
  • 80