Home > Software engineering >  Checked multiple times and also typecasted explicitly to avoid errors but still this program showing
Checked multiple times and also typecasted explicitly to avoid errors but still this program showing

Time:12-03

Trying to implement default constructor and some basic functions. Although the logic behind this program is clear but I don't know why the output is wrong every time. To avoid any kind of issues I typecasted explicitly but still seems like error hasn't resolved.

import java.util.*;

class Facebook {
  Facebook() {
    System.out.printf("Welcome to Facebook.\n");
  }

  boolean Login(String uName, String pWord) {
    if(uName == "knownassurajit" && pWord == "password")
      return true;
    else
      return false;
  }

  public static void main(String[] args) {
    Facebook user = new Facebook();
    Scanner scanner = new Scanner(System.in);

    System.out.printf("Username: ");
    String username = scanner.next();
    System.out.printf("Password: ");
    String password = scanner.next();

    //System.out.println(username.length()   " "   password.length());

    if(user.Login((String) username, (String) password)) {
      System.out.println("Successfully logged in.");
    }
    else {
      System.out.println("Username or Password incorrect.");
    }
  }
}

This code will work perfectly with equals() function.

import java.util.*;

class Facebook {
  Facebook() {
    System.out.printf("Welcome to Facebook.\n");
  }

  boolean Login(String uName, String pWord) {
    if(uName.equals("user") && (pWord.equals("p@$$w0rd")))
      return true;
    else
      return false;
  }

  public static void main(String[] args) {
    Facebook user = new Facebook();
    Scanner scanner = new Scanner(System.in);

    System.out.printf("Username: ");
    String username = scanner.next();
    System.out.printf("Password: ");
    String password = scanner.next();

    if(user.Login((String) username, (String) password)) {
      System.out.println("Successfully logged in.");
    }
    else {
      System.out.println("Username or Password incorrect.");
    }
  }
}

CodePudding user response:

The ==-Operator checks the Reference in Java, so that'll only work if your Objects are Identical, which they aren't. You need to use the equals() method to check if the contents are the same.

  • Related