如何将其转换为使用数组列表而不是数组?

时间:2014-01-23 04:12:46

标签: java arrays

此代码对数字进行随机抽样,将它们插入数组,计算奇数,然后让用户选择一个整数以查看它是否匹配。现在只使用数组,这很好用,但我想将其转换为与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;

    }
}

1 个答案:

答案 0 :(得分: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;
}