vendredi 3 décembre 2021

Checked multiple times and also typecasted explicitly to avoid errors but still this program showing wrong results. What to do?

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

Aucun commentaire:

Enregistrer un commentaire