我試圖製作一個程序,要求用戶創建一個人或一組人,併爲其分配名稱和年齡。所以我做了一個構造函數「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);
}
}
爲什麼你需要三個獨立的'Scanner'對象從鍵盤讀?你知道'ArrayList'嗎? – 2014-10-17 02:34:30
你實際上並沒有創建新的'Try'對象,你只需設置靜態字段即可。 – 2014-10-17 02:58:03