You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java实现登录功能多次检查并显式类型转换仍输出错误如何解决?

Java登录功能返回结果异常问题

尝试实现默认构造方法及基础登录功能时,程序逻辑无明显问题但输出结果始终不正确,多次检查代码、额外增加显式类型转换后问题仍未解决。

问题代码

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

根因分析

  • Java中==运算符用于引用类型对比时,比较的是两个对象的内存地址是否相同,而非对象存储的内容
  • 通过Scanner输入获取的字符串对象,与代码中定义的字符串字面量属于不同的内存对象,即便内容完全一致,用==判断也会返回false
  • 额外增加的显式类型转换操作不影响对比逻辑,无法解决问题

修复方法

将Login方法中的字符串对比逻辑从==替换为String类的equals()方法,该方法会直接对比两个字符串的实际内容是否匹配。

修复后代码

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

内容的提问来源于stack exchange,提问作者surajit das

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 11:45:04