首页 > 解决方案 > read from a file i created with random ints and place into an array and display values

问题描述

a. Reopen the file for reading. b. Read each value from the file and place into an array. c. Display each value AFTER it is placed into the array (i.e. access value from array to display).

d. Find and display the largest two distinct numbers in the array. a. It is possible for the array to contain duplicates which causes 1st largest = 2nd largest. b. Skip duplicates for 2nd largest! See tips section for details. e. Sort the array into descending order (largest to smallest). When performing this sort: a. You can use the sort method in the Arrays class b. You cannot use the reverseOrder method on the Collections class c. You must manually sort the values into descending order. d. Manually sorting means you must write the code that does the sorting without using any methods other than Arrays.sort() f. Display the updated array after manually sorting into descending order.

I have tried using different methods even though it is not necessary for this problem. When I try and compile all I get for my array is [] and no values.

    int max = 100;
    int min = 1;
    Random randomNum = new Random();
    File fileName = new File("assignment1.txt");
    PrintWriter resultsFile = new PrintWriter (fileName);
    System.out.println("Generating random values and writing to a file: ");

    for(int i = 1; i < 26; i++) {
        int showMe = min + randomNum.nextInt(max);

        System.out.println("Writing to a file: ");
        System.out.println(showMe);



        resultsFile.println(showMe);

    }
    resultsFile.close();
    System.out.println("Reading values from file and placing into an array");
    int[] data = readFiles("assignmnent1.txt");
    System.out.println(Arrays.toString(data));
}

public static int[] readFiles(String fileName) {

    try {

        //File f = new File(fileName);
        Scanner s = new Scanner (fileName);
        int ctr = 25;

        while (s.hasNextInt()) {
            ctr++;
            s.nextInt();
        }
        int [] arr = new int[ctr];



        return arr;

    }
    catch (Exception e) {
        return null;
    }

I am not sure where I am going wrong and why it will not display the values in the array.

标签: javaarraysfile

解决方案


在您的 readFiles 函数中,您初始化了数组,但没有用任何值填充它。

        int [] arr = new int[ctr];



        return arr;

推荐阅读