2016-08-30 180 views
-4

我的代碼有問題。此代碼應檢查登錄名和密碼。問題是else if語句顯示錯誤的輸出。例如,當我輸入用戶名== admin和密碼== 1234時,它顯示的用戶名不正確。Java ==!= && ||運營商?

import java.io.*; 

public class login 
{ 
public static void main(String [] args) throws IOException 
{ 
    String username = "admin"; 
    String password = "123"; 

    BufferedReader inData = new BufferedReader(new InputStreamReader(System.in)); 

    System.out.print("Enter username : "); 
    username = inData.readLine(); 

    System.out.print("Enter password : "); 
    password = inData.readLine(); 

    if((username == "admin") && (password == "123")) 
    { 
     System.out.println("Welcome " + username + "\n*** Login Sucessfully ***" + "\n*** Access Granted ***"); 
    } 
    else if((username != "admin") && (password == "123")) 
    { 
     System.out.println("Sorry, username is incorrect!\n*** Access Denied ***"); 
    } 
    else if((username == "admin") && (password != "123")) 
    { 
     System.out.println("Sorry, password is incorrect!\n*** Access Denied ***"); 
    } 
    else if((username != "admin") && (password != "123")) 
    { 
     System.out.println("Sorry, username and password is incorrect!\n*** Access Denied ***"); 
    } 
} 
} 
+1

當你比較字符串時你明白==和equals的區別嗎? – Li357

+0

@Kero Kero ==用於比較用於比較String的int或float值(數字)和.equals()方法。 – yash

+0

@AndrewL。哦,以前從來不知道。現在我明白了==和.equals之間 –

回答

0

.equals().equals()方法用於在這種情況下比較字符串。例如
username.equals("admin"),它比較變量用戶名的值和值「admin」,這裏都是字符串