2013-03-12 71 views
-4

我可以在主類中做這樣的事嗎?創建多個對象

Scanner sc = new Scanner(System.in); 
System.out.println("message 1"); 
int nbre1 = sc.nextInt(); 
sc.nextLine(); 
System.out.println("message 2"); 
int nbre2 = sc.nextInt(); 
sc.nextLine(); 
System.out.println("message 3"); 
int nbre3 = sc.nextInt(); 
sc.nextLine(); 

Obj o = new Obj(nbre1, nbre2, nbre3); 

// print a message "do you want to create another object?" 

如果是,我可以再次顯示消息但不影響其他對象的變量,例如: O2?

+1

是的,你做這樣的事情,很明顯我想既然你已經做了:-) – Thihara 2013-03-12 06:30:52

+0

我怎麼都找不到! – mpluse 2013-03-12 06:31:48

+0

當然,它不會工作,因爲'sc'無處定義。 – dokaspar 2013-03-12 06:32:19

回答

0

您可以在函數中編寫上述代碼並在循環中調用函數。 事情是這樣的......

List<Obj> objects = new ArrayList<Obj>(); 
while(true){ 
    Obj o = new Obj(); 
    boolean continueBool = readInputs(o); 
    objects.add(o); 
    if(!continueBool){ 
     break; 
    } 
} 

private boolean readInputs(Obj o){ 
// code to read inputs and create Obj object. If the user wants to create more objects, return TRUE else return FALSE 
    Scanner sc = new Scanner(System.in); 
    System.out.println("message 1"); 
    int nbre1 = sc.nextInt(); 
    sc.nextLine(); 
    System.out.println("message 2"); 
    int nbre2 = sc.nextInt(); 
    sc.nextLine(); 
    System.out.println("message 3"); 
    int nbre3 = sc.nextInt(); 
    // set values nbre1, nbre2 and nbre3 to 'o' 
    System.out.println("Do you want to repeat ?"); 
    String inStr = sc.nextLine();  
    if(inStr.equalsIgnoreCase("yes")) { 
     return true; 
    } else { 
     return false; 
    } 
} 
+0

我怎樣才能每次更改參考? – mpluse 2013-03-12 06:35:42

+0

'boolean continue'語句是**災難**。我建議你使用IDE進行編碼並直接從那裏粘貼。它會告訴你爲什麼它錯了。 – SudoRahul 2013-03-12 06:42:45

+0

@ R.J道歉。糾正。 – Apurv 2013-03-12 06:44:25