2011-12-09 111 views
-4

感謝所有幫助人員,但現在問題的性質已經根據Patrick的建議改變了。循環正在運行,但它似乎並未將輸入存儲到各個陣列。數據不斷被替換到陣列列表中,而不是進入陣列列表中的下一個位置任何建議?無法將數據存儲在arrayLists中?

import java.util.ArrayList; 
import java.util.Scanner; 
public class Arrray { 
    public static void main(String [] args){ 

     ArrayList<String> names; 
     ArrayList<String> addr; 

     do { 
      names = new ArrayList<String>(); 
      addr = new ArrayList<String>(); 
      Scanner userInput = new Scanner(System.in); 
      System.out.println("Name and Adreess are: " + names.size() + "**" 
        + addr.size()); 
      System.out.println("please Enter Your Name :"); 
      names.add(userInput.next()); 
      System.out.println("please enter your Address :"); 
      addr.add(userInput.next()); 

      System.out.println("Do you want to add another entry? :(y/n)"); 
      String ans =userInput.next(); // get the value from the user using scanner class 
      if(ans.equals("n") || ans.equals("N")) 
       break; 

      } while (true); 
     int n = names.size(); 
     int a = addr.size(); 
     for(int i =0; i<n && i<a; i++) 
      System.out.println("Name and address are as below: "+ names.get(i)+"**"+ addr.get(i)); 

    } 
} 
+1

誰是帕特里克?在編輯之前我們看不到任何東西,所以我們不確定發生了什麼。你是否創建了一個新問題而不是編輯前一個問題?您應該添加一個標籤,指定您正在使用的語言。 –

+2

你能否使用標點符號來識別句子的開始和結束? –

回答

1

您每次通過循環時都創建一個新的ArrayList。這意味着最後一個數組只包含最後一個元素。 改爲在循環之前創建它們。

2

您的代碼每次運行時都會重新初始化ArrayList。你需要把它從循環中取出。

import java.util.ArrayList; 
import java.util.Scanner; 
public class Arrray { 
    public static void main(String [] args){ 

     ArrayList<String> names = new ArrayList<String>(); 
     ArrayList<String> addr = new ArrayList<String>(); 

     do { 
      //names = new ArrayList<String>(); take this out 
      //addr = new ArrayList<String>(); // take this out 
      Scanner userInput = new Scanner(System.in); 
      System.out.println("Name and Adreess are: " + names.size() + "**" 
        + addr.size()); 
      System.out.println("please Enter Your Name :"); 
      names.add(userInput.next()); 
      System.out.println("please enter your Address :"); 
      addr.add(userInput.next()); 

      System.out.println("Do you want to add another entry? :(y/n)"); 
      String ans =userInput.next(); // get the value from the user using scanner class 
      if(ans.equalsIgnoreCase("n")) 
       break; 

      } while (true); 
     int n = names.size(); 
     int a = addr.size(); 
     for(int i =0; i<n && i<a; i++) 
      System.out.println("Name and address are as below: "+ names.get(i)+"**"+ addr.get(i)); 

    } 
}