lancer
lancer

Reputation: 133

Store ints into array from a file and find mean JAVA

In this program, you will find a menu with options to perform different functions on an array. This array is taken from a file called "data.txt". The file contains integers, one per line. I would like to create a method to store those integers into an array so I can call that method for when my calculations need to be done. Obviously, I have not included the entire code (it was too long). However, I was hoping that someone could help me with the first problem of computing the average. Right now, the console prints 0 for the average because besides 1, 2, 3 being in the file, the rest of the array is filled with 0's. The average I want would be 2. Any suggestions are welcome. Part of my program is below. Thanks.

public static void main(String[] args) throws FileNotFoundException {
    Scanner sc = new Scanner(System.in);
    System.out.println("Welcome to Calculation Program!\n");
    startMenus(sc);

}

private static void startMenus(Scanner sc) throws FileNotFoundException {
    while (true) {
        System.out.println("(Enter option # and press ENTER)\n");

        System.out.println("1. Display the average of the list");
        System.out.println("2. Display the number of occurences of a given element in the list");
        System.out.println("3. Display the prime numbers in a list");
        System.out.println("4. Display the information above in table form");
        System.out.println("5. Save the information onto a file in table form");
        System.out.println("6. Exit");

        int option = sc.nextInt();

        sc.nextLine();

        switch (option) {
            case 1:
                System.out.println("You've chosen to compute the average.");
                infoMenu1(sc);
                break;
            case 2:
                infoMenu2(sc, sc);
                break;
            case 3:
                infoMenu3(sc);
                break;
            case 4:
                infoMenu4(sc);
                break;
            case 5:
                infoMenu5(sc);
                break;
            case 6:
                System.exit(0);
            default:

                System.out.println("Unrecognized Option!\n");
        }

    }
}

private static void infoMenu1(Scanner sc) throws FileNotFoundException {
    File file = new File("data.txt");
    sc = new Scanner(file);

    int[] numbers = new int[100];

    int i = 0;

        while (sc.hasNextInt()) {
            numbers[i] = sc.nextInt();
            ++i;
        }

    System.out.println("The average of the numbers in the file is: " + avg(numbers));
}

public static int avg(int[] numbers) {
    int sum = 0;
    for (int i = 0; i < numbers.length; i++) {
        sum = (sum + numbers[i]);
    }
    return (sum / numbers.length);
}

Upvotes: 1

Views: 1563

Answers (4)

neonleo
neonleo

Reputation: 192

Please change your average function in such a way

  private static void infoMenu1(Scanner sc) throws FileNotFoundException {
    .
    .
    .
    System.out.println("The average of the numbers in the file is: " + avg(numbers,i));
  }

  public static int avg(int[] numbers,int length) {
    int sum = 0;
    for (int i = 0; i < length; i++) {
        sum = (sum + numbers[i]);

    }
    return (sum / length);
}

While calling average function pass i (which you counted in infoMenu1 for number of entries in data.txt) as well and use that in loop and dividing the sum. with this your loop will not run for 100 iterations and code of lines also reduced.

Upvotes: 0

Cratylus
Cratylus

Reputation: 54074

Just modify your method as follows:
public static int avg(int[] numbers, int len) where len is the actual numbers stored.
In your case you call:

System.out.println("The average of the numbers in the file is: " + avg(numbers, i));  

And in your code for average:

 for (int i = 0; i < len; i++) {
        sum = (sum + numbers[i]);
    }  

I.e. replace numbers.length with len passed in

And do return (sum / len);

Upvotes: 1

DaoWen
DaoWen

Reputation: 33019

Instead of using a statically-sized array you could use a dynamically-sized List:

import java.util.List;
import java.util.LinkedList;

// . . .

private static void infoMenu1(Scanner sc) throws FileNotFoundException {
    File file = new File("data.txt");
    sc = new Scanner(file);

    List<Integer> numbers = new LinkedList<Integer>();

    while (sc.hasNextInt()) {
        numbers.add(sc.nextInt());
    }

    System.out.println("The average of the numbers in the file is: " + avg(numbers));
}

public static int avg(List<Integer> numbers) {
    int sum = 0;
    for (Integer i : numbers) {
        sum += i;
    }
    return (sum / numbers.size());
}

This has added the benefit of allowing you to read in more than 100 numbers. Since the LinkedList allows you to perform an arbitrary number of add operations, each in constant time, you don't need to know how many numbers (or even an upper-bound on the count) before reading the input.

As kkonrad also mentioned, you may or may not actually want to use a floating-point value for your average. Right now you're doing integer arithmetic, which would say that the average of 1 and 2 is 1. If you want 1.5 instead, you should consider using a double to compute the average:

public static double avg(List<Integer> numbers) {
    double sum = 0;
    for (Integer i : numbers) {
        sum += i;
    }
    return (sum / numbers.size());
}

Upvotes: 1

kkonrad
kkonrad

Reputation: 1262

I think sum should be a double and double should be the return type of your avg function

Upvotes: 0

Related Questions