Java中的条件语句问题

问题描述

一个非常简单的登录系统是我想到的使用Java条件语句的更好方法之一。 我要做的就是比较两个字符串变量,看来在此过程中出了点问题。它总是只会出现在最后的“ else”语句中,并且我已经进行了很多故障排除,结果表明在出现条件时,用户名密码实际上是相同的。

以下是代码

import java.util.Scanner;

public class HelloWorld {

    // Pre-defined username and password requirements
    String requiredUsername = "test";
    String requiredPassword = "test";

    // Initializes the textinput
    Scanner input = new Scanner(system.in);

    public static void main(String[] args) {

        // Creates a new "object" of the main program called loginpage 
        HelloWorld logingpage = new HelloWorld();

        // Starts the "start" method
        logingpage.start();

    }

    public void start() {

        // // Main Screen in console
        // System.out.println("+-----------------------------------------------+"
        //                + "|                                               |"
        //                + "|          Welcome to the Login Screen          |"
        //                + "|                                               |"
        //                + "+-----------------------------------------------+");

        // Prompts the user for a username and gathers it
        System.out.print("[*] Please enter Username\n>>> ");
        String username = input.nextLine();
        System.out.println("");

        // Prompts the user for a password and gathers it
        System.out.print("[*] Please enter Password\n>>> ");
        String password = input.next();
        System.out.println("");

        // Conditionals to check username and password
        if (username == requiredUsername && password == requiredPassword) {
            System.out.println("[*] The secret message is: The eagle has landed!");
        } else if (username == requiredUsername && password != requiredPassword) {
            System.out.println("[*] ERROR,Password Not Valid");
        } else if (username != requiredUsername && password == requiredPassword) {
            System.out.println("[*] ERROR,Username Not Valid");
        } else {
            System.out.println("[*] ERROR,All Credentials Invalid");
        }

        // input.close();
    
    }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)