【问题标题】:how to access variables from private bodies in java如何从java中的私有主体访问变量
【发布时间】:2015-06-10 19:13:46
【问题描述】:
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 variables global private


【解决方案1】:

目前您正在声明 本地 变量。这些仅在您执行该方法时存在。听起来它们实际上应该是类中的 instance 变量(字段):

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);

...不过,尚不清楚这些是否真的应该是单独的方法。为什么询问 auth 信息的方法没有验证它?请注意,您使用的验证是一个简单的验证,它实际上并没有检查用户名/密码组合是否 正确 - 它只是检查它是否 可能 正确(与检查最小密码长度等相同的验证)。

【讨论】:

  • 我不太确定我是否跟随你“它们实际上应该是你班级中的实例变量(字段)”我一直在努力学习 java 我已经学习了 1 周并试图掌握基础知识,所以对您使用的所有术语不太熟悉,但我相信我理解您刚才提到的大部分内容,谢谢
  • @Isuckatprogramming:您可能应该找到有关 Java 中不同类型变量的教程。我现在在移动设备上,这有点棘手,但只需搜索 Java 教程变量即可。
  • 也许这篇文章会有所帮助:docs.oracle.com/javase/tutorial/java/nutsandbolts/…,它介绍了 Java 中可用的不同类型的变量。您使用的是局部变量,Jon 建议您使用的是实例变量。希望对您有所帮助。
猜你喜欢
  • 2012-05-09
  • 1970-01-01
  • 1970-01-01
  • 2016-03-08
  • 1970-01-01
  • 2011-03-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多