2014-01-23 91 views
-2

這段代碼需要對數字進行隨機抽樣,將它們插入數組中,計算奇數,然後讓用戶選擇一個整數來查看它是否匹配。這對於數組來說很好,但我想將它轉換爲ArrayLists。最簡單的方法是什麼?如何將此轉換爲數組列表而不是數組?

import java.util.Scanner; 
import java.util.Random; 

public class ArrayList { 
    public static void main(String[] args) { 
     // this code creates a random array of 10 ints. 
     int[] array = generateRandomArray(10); 

     // print out the contents of array separated by the delimeter 
     // specified 

     printArray(array, ", "); 

     // count the odd numbers 

     int oddCount = countOdds(array); 

     System.out.println("the array has " + oddCount + " odd values"); 
     // prompt the user for an integer value. 
     Scanner input = new Scanner(System.in); 
     System.out.println("Enter an integer to find in the array:"); 
     int target = input.nextInt(); 

     // Find the index of target in the generated array. 

     int index = findValue(array, target); 

     if (index == -1) { 
      // target was not found 
      System.out.println("value " + target + " not found"); 
     } else { 
      // target was found 
      System.out.println("value " + target + " found at index " + index); 
     } 

    } 

    public static int[] generateRandomArray(int size) { 
     // this is the array we are going to fill up with random stuff 
     int[] rval = new int[size]; 

     Random rand = new Random(); 

     for (int i = 0; i < rval.length; i++) { 
      rval[i] = rand.nextInt(100); 
     } 

     return rval; 
    } 

    public static void printArray(int[] array, String delim) { 

     // your code goes here 
     for (int i = 0; i < array.length; i++) { 
      System.out.print(array[i]); 
      if (i < array.length - 1) 
       System.out.print(delim); 
      else 
       System.out.print(" "); 
     } 
    } 

    public static int countOdds(int[] array) { 
     int count = 0; 

     // your code goes here 
     for (int i = 0; i < array.length; i++) { 
      if (array[i] % 2 == 1) 
       count++; 
     } 

     return count; 
    } 

    public static int findValue(int[] array, int value) { 
     // your code goes here 
     for (int i = 0; i < array.length; i++) 
      if (array[i] == value) 
       return i; 
     return -1; 

    } 
} 
+3

嗯...首先閱讀Javadoc的'ArrayList'來看到所需的更改是最小的? –

+0

您可能需要參考這篇文章[如何從數組(T [])創建ArrayList(ArrayList )] http://stackoverflow.com/questions/157944/how-to-create-arraylist-arraylistt-從陣列叔 –

回答

0

我重寫了你的兩個函數,也許它們對你有用。

public static List<Integer> generateRandomList(int size) { 
    // this is the list we are going to fill up with random stuff 
    List<Integer> rval = new ArrayList<Integer>(size); 
    Random rand = new Random(); 
    for (int i = 0; i < size; i++) { 
     rval.add(Integer.valueOf(rand.nextInt(100))); 
    } 
    return rval; 
} 

public static int countOdds(List<Integer> rval) { 
    int count = 0; 
    for (Integer temp : rval) { 
     if (temp.intValue() % 2 == 1) { 
      count++; 
     } 
    } 
    return count; 
}