2015-07-21 79 views
0

這是我的代碼:如何將循環中的值輸入到數組列表中?

public static void main(String[] args) { 
    System.out.println("Please enter the number of values you would like to enter: "); 
    Scanner scan = new Scanner(System.in); 
    int intNumberOfNumbers = scan.nextInt(); 

    for (int i = 0; i < intNumberOfNumbers; i++) { 
     System.out.println("Please enter a value for index " + i + ":"); 
     int intValue = scan.nextInt(); 
    } 
} 

我想要做的是創造,詢問他們想要多少個值進入和任何該值,這是它多少次詢問號碼輸入掃描儀。問題出在我問這個問題後,我該如何將數字添加到數組列表中?

+1

你如何添加東西的'ArrayList',無論是內部還是外循環? –

+0

您是閱讀文檔還是查看任何示例? – tnw

+1

請仔細閱讀數組的基礎知識,在上面的例子中你沒有創建任何ArrayList –

回答

-1
public static void main(String[] args) { 
    System.out.println("Please enter the number of values you would like to enter: "); 
    Scanner scan = new Scanner(System.in); 
    int intNumberOfNumbers = scan.nextInt(); 
    ArrayList<Integer> myArray= new ArrayList<>(); 
    for (int i = 0; i < intNumberOfNumbers; i++) { 
     System.out.println("Please enter a value for index " + i + ":"); 
     int intValue = scan.nextInt(); 
     myArray.add(intValue); 
    } 
} 
0
public static void main(String args[]){ 
    Scanner sc=new Scanner(System.in); 
    int numOfInput=sc.nextInt(); 
    ArrayList<Integer> array=new ArrayList<Integer>(); 

    while(numOfInput-->0){ 
     array.add(sc.nextInt());  
    } 
}