2016-07-29 239 views
-1

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

我想從Class_b得到usernamepassword值,並將其存儲到字符串變量usernamepassword在Main.java中。

+0

你顯然是將用戶名和密碼傳入登錄函數FROM main,爲什麼你需要將它返回給main? – redunderthebed

回答

2

你可以返回一個自定義的Java類型,或只是String數組。喜歡的東西

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

這也不清楚爲什麼你會傳遞String(縣)你的方法,你忽略它們並返回新的值。

+0

謝謝。它幫助我很多 –

1

第一步:創建分類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; 
} 

}

第二步:在Main.java

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

感謝。

+0

使用getter和setter的好主意。這有助於我理解吸氣和吸氣者的作用 –

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