从另一个类中获取值

时间:2016-07-29 02:25:17

标签: java return

Main.java

 public static void main(String[] args) {
    String username ="";
    String password = "";
    Class_b b = new Class_b();
    b.login("username","password");
 }

Class_b.java

public String login(String user, String pass) {
      String username = "admin";
      String password = "password";
      return username+" "+password;
}

我想从username获取passwordClass_b值,并将其存储到Main.java中的字符串变量usernamepassword。< / p>

3 个答案:

答案 0 :(得分:2)

您可以返回自定义java类型,或仅返回String 1 的数组。像

这样的东西

Class_b.java

public String[] login(String user, String pass) {
      String username = "admin";
      String password = "password";
      return new String[] { username, password };
}

然后您可以像

一样调用它
public static void main(String[] args) {
    String username ="";
    String password = "";
    Class_b b = new Class_b();
    String[] arr = b.login(username,password);
    if (arr.length > 1) {
        username = arr[0];
        password = arr[1];
    }
    System.out.println("username=" + username + ", password=" + password);
}

1 还不清楚为什么要将String(s)传递给您的方法,忽略它们并返回新值。

答案 1 :(得分:2)

您可以简单地使用spilled()方法 例如,

String temp = b.login("username","password");
String login[] = temp.split("\\s+");
/*spilts username & password separated by space*/
System.out.print(login[0]); //prints username
System.out.println(login[1]); //prints password

答案 2 :(得分:1)

Step1:创建类Class_b:

public class Class_b {

private String username;

private String password;

public Class_b() {
    this.username = "admin";
    this.password = "password";
}

/**
 * @return the username
 */
public String getUsername() {
    return username;
}

/**
 * @param username
 *            the username to set
 */
public void setUsername(String username) {
    this.username = username;
}

/**
 * @return the password
 */
public String getPassword() {
    return password;
}

/**
 * @param password
 *            the password to set
 */
public void setPassword(String password) {
    this.password = password;
}

}

Step2:在Main.java中

public static void main(String[] args) {
    Class_b class_b = new Class_b();
    username = class_b.getUsername();
    password = class_b.getUsername();
}

感谢。