2014-10-17 27 views
0

我試圖製作一個程序,要求用戶創建一個人或一組人,併爲其分配名稱和年齡。所以我做了一個構造函數「Try」和一個方法「AskUser」。AskUser()我使用了do/while循環,要求用戶輸入一個名字,一個年齡以及他是否想創建另一個人。現在,每次循環運行時如何獲取輸入數據,並將其發送給構造函數以使用它創建新對象?以及這些新對象將如何被調用?調用構造函數並從掃描器方法爲其分配值

import java.util.Scanner; 
public class Try{ 
    static String name; 
    static int age; 
    static Scanner a = new Scanner(System.in); 
    static Scanner b = new Scanner(System.in); 
    static Scanner c = new Scanner(System.in); 
    public Try(String name, int age){ 
     this.name=name; 
     this.age= age; 
     System.out.println("this is "+name+", and he is "+age+" old."); 
    } 
    public static void AskUSer(){ 
     int x=0; 
     do {System.out.print("what's the name of the person ?"); 
      name= a.nextLine(); 
      System.out.print("how old is he? "); 
      age= b.nextInt(); 
      System.out.print("would u like to creat another person "); 
      String yes = c.nextLine(); 
      if(!(yes.equals("yes"))){x++;} 
     } while(x==0); 
    } 
    public static void main (String[] args){ 
     AskUSer(); 
     System.out.print(age+ " "+ name); 
    } 
}  
+0

爲什麼你需要三個獨立的'Scanner'對象從鍵盤讀?你知道'ArrayList'嗎? – 2014-10-17 02:34:30

+0

你實際上並沒有創建新的'Try'對象,你只需設置靜態字段即可。 – 2014-10-17 02:58:03

回答

0

您可以在AskUSer中構造新對象並將其作爲返回值返回。因此,代碼看起來像:

public static YourObject AskUSer() { 
    ... 
} 
0
從你如何讀取用戶

不談,

這將是適當的做一類.. 類似:

class Person { 
    private String name; 
    private int age; 

    Person(String name, int age) { 
     this.name = name; 
     this.age = age; 
    } 
    public String getName() { 
     return this.name; 
    } 
    public int getAge() { 
     return this.age; 
    } 
} 

之前進入循環 您可以使用ArrayList來容納人

ArrayList<Person> people = new ArrayList<Person>(); 

,並在每次閱讀時間投入..實例化一個Person對象並把它添加到ArrayList

類似:

Person pr=new Person(name,age); 
people.add(pr); 
+0

1.ok,創建一個類...我的構造函數有什麼問題?爲什麼我需要一堂課? – Sasha 2014-10-17 13:19:49

+0

2.' Person pr =新人(姓名,年齡); people.add(PR); '這個循環會不會一遍又一遍地重寫Person個人信息? – Sasha 2014-10-17 13:25:54

相關問題