[英]JAVA How to use aspects of newly returned object in a non-static method of same class
我正在處理一個創建“代理”對象的分配,該對象具有通過set和get方法中的隨機生成器隨機分配的大約六個屬性。
我遇到的最大問題是,每次嘗試構造涉及Agent1的方法時,我都會不斷收到“無法解決Agent1”錯誤
public class Agent
{
// properties of Agents-to-be, set to private to keep things safe
private String Gender;
private String Birthday;
private String Name;
private String CityBorn;
private String CityNow;
private String Major;
private String filename;
private String Age;
// sets 3 variables that will be used throughout the program
final String M = "Male" ;
final String F = "Female" ;
final Random Schrodinger= new Random();
public static void main(String[] args)
{
generateAgent();
Agent1.WhoAreYou();
}
// this Method invokes all the set methods(not shown) that set the value of the above
// private strings.
public static Agent generateAgent() {
Agent Agent1 = new Agent();
Agent1.setGender();
Agent1.setBirthday();
Agent1.setName();
Agent1.setCityBorn();
Agent1.setCityNow();
Agent1.setMajor();
return Agent1;
}
下一種方法是我遇到的麻煩。 不管如何更改,總是收到錯誤消息“無法解析Agent1”,我認為這只是意味着對象Agent 1停止了我的靜態方法之外的對象。 此方法僅用於分配的這一部分,在以后的部分中,我將不得不調用generateAgent方法來創建兩個代理實例以相互交談。 否則,我嘗試將這兩種方法結合起來,並且似乎可以那樣工作,所以我只需要一種通過它們保存對象的方法。
public void WhoAreYou()
{
Agent1.getGender();
Agent1.getBirthday();
Agent1.getName();
Agent1.getCityBorn();
Agent1.getCityNow();
Agent1.getMajor();
Agent1.getMajor();
Agent1.sayHello();
Agent1.sayCityBorn();
Agent1.sayGender();
Agent1.sayCityNow();
Agent1.sayMajor();
}
分別地,這是每個set和get方法的示例,以防萬一您認為它們是造成我問題的原因。 他們都很相似
// The set Methods. These methods either use a random number generator to create random values for our
// agents properties, or use the WordList class to do so.
public void setGender()
{
// next.int(n) gives a random number between 0 and n-1, so nextInt(2)'s range is 0-1
int i = Schrodinger.nextInt(2);
// "if/else" statement, shortened for readability
this.Gender = ((i==1)?M:F);
}
/** the "get" methods.These are all one line long and are just used to supply inputs for later code
* All of them return "this.('methodname - get')." The this. prefix serves to insure each method is
* only returning a characteristic of one particular object
**/
public String getGender()
{
return this.Gender;
}
“ sayX”全都依賴於前兩種方法的輸出,並且當我將它們與set和get都用相同的方法時可以工作
public void howOldAreYou()
{
System.out.println( this.Name + " says: I am " + this.Age + " Years old ") ;
}
在您的主要方法中,您有這樣的代碼
generateAgent();
Agent1.WhoAreYou();
但是,您的方法generateAgent()
返回對名為Agent1
的類型為Agent
的對象實例的Agent1
。 您的名字無關緊要,對象類型和狀態很重要-但是,根據您的命名,請嘗試此操作
Agent Agent1 = generateAgent(); // this Agent Agent1 refers to the same Agent
// from generateAgent (which was also named Agent 1).
Agent1.WhoAreYou();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.