2015-04-06 87 views
0
public void TheBank() { 
Scanner Sc = new Scanner(System.in); 
    System.out.println("Please Enter your Username and Password"); 
    MemoryStorage();// Stores the Username and Password in the system. 
    VariableCompare();// Compares the Username and Password to see if they match or do not 
} 

private void MemoryStorage(){// this should just be here to store the variables username and password 
    Scanner Sc = new Scanner(System.in); 
    String username = Sc.nextLine(); 
    String password = Sc.nextLine(); 
} 
private void VariableCompare() {// this should compare to see if they match or dont and print the results 
    if (username.equals (password){ 
     System.out.println("Please try again your Username and Password cannot be the same"); 
    } else { 
     System.out.println (" Your username is:" + username); 
     System.out.println(" Your password is:" + password); 
    } 
} 
} 

我的問題是身體(MemoryStorage)來自私人機構的變量,我想它來保存用戶名和密碼,從而使其他機構可以使用它與藏漢他們的計算進行。目前,變量的用戶名和密碼不被接受到其他機構,我想知道如何讓這兩個變量可供所有機構使用。如何訪問在java中

+0

然後將用戶名和密碼設置爲實例變量。 – Rajesh 2015-04-06 11:42:18

回答

3

目前您聲明本地變量。那些只在執行方法時才存在。這聽起來像他們實際上應該是實例變量(字段)類中:

public class Whatever { 
    private String username; 
    private String password; 

    // Methods which assign to username/password and read from them 
} 

你也應該對Java的命名約定讀了,想想如何更命名你的方法沿着什麼樣的線他們實際上在做。哦,並考慮將Scanner轉換爲您當前的MemoryStorage方法,而不是創建一個新的 - 我已經看到各種問題,當人們創建具有相同基礎流的多個Scanner實例時會出現各種問題。

作爲實例字段的替代方法,您可以考慮使用方法的返回值。例如:

AuthenticationInfo auth = requestUserAuthentication(scanner); 
validateAuthentication(auth); 

...雖然,但不清楚這些應該真的是單獨的方法。爲什麼要求驗證身份驗證信息的方法?請注意,您使用的驗證是一個簡單的一個實際不檢查用戶名/密碼組合是正確 - 它只是檢查它的可能正確的(相同類型的驗證作爲將檢查最小密碼長度等)。

+0

我不太確定,我跟着你「他們實際上應該是你班上的實例變量(字段)」一直在努力學習java 1個星期了,並試圖掌握基本知識,所以不太熟悉與你正在使用的所有術語,但我相信我理解你剛纔提到的大多數,謝謝 – IsuckAtProgramming 2015-04-06 11:55:37

+0

@Isuckatprogramming:你應該找到關於Java中不同類型的變量的教程。我現在正在使用移動設備,使其變得更加棘手,但只需搜索Java教程變量即可。 – 2015-04-06 11:57:07

+0

也許這篇文章將幫助:https://docs.oracle.com/javase/tutorial/java/nutsandbolts/variables.html,介紹了在Java中可用的不同類型的變量。你使用的是局部變量,Jon建議你使用的是實例變量。希望能幫助到你。 – zpon 2015-04-06 13:33:51