2015-04-06 53 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