简体   繁体   中英

Can't find five lowest values in an array…max works while min array is not assigned values

I'm very close to completing this, all I need is help on finding the five lowest values from a text file by using arrays. I figured out how to find the five highest values, but my min array to find the lowest values always outputs five 0's.

Output: //obviously dependent on individual text file

Total amount of numbers in text file is 10

Sum is: 1832

1775 14 9 9 7 //max

0 0 0 0 0 //min

Any help is much appreciated!

import java.util.Scanner; 
import java.io.*;

public class HW3
{
   public static void main(String[] args) throws IOException
   {
  File f = new File("integers.txt");
  Scanner fr = new Scanner(f);

    int sum = 0;
    int count = 0;
    int[] max = new int[5];
    int[] min = new int[5];
    int temp;

  while(fr.hasNextInt())
  {
        count++;        
        fr.nextInt();
  }

    Scanner fr2 = new Scanner(new File("integers.txt"));
    int numbers[] = new int[count];

    for(int i=0;i<count;i++)
  {
    numbers[i]=fr2.nextInt(); //fills array with the integers
  }

    for(int j:numbers)//get sum
    {
        sum+=j;
    }

    for (int j=0; j < 5; j++) //finds five highest
    {
        for (int i=0; i < numbers.length; i++)
            {
                if (numbers[i] > max[j])
                {
                    temp = numbers[i];
                    numbers[i] = max[j];
                    max[j] = temp;
                }
            }   
    }

    for (int j=0; j < 5; j++) //finds five lowest...array not assigned values
    {
        for (int i=0; i < numbers.length; i++)
            {
                if (numbers[i] < min[j])
                {
                    temp = numbers[i];
                    numbers[i] = min[j];
                    min[j] = temp;
                }
            }   
    }

    System.out.println("Total amount of numbers in text file is " + count);
    System.out.println("Sum is: " + sum);
    System.out.println(max[0] + " " + max[1] + " " + max[2] + " " + max[3] + " " + max[4]);
    System.out.println(min[0] + " " + min[1] + " " + min[2] + " " + min[3] + " " + min[4]);

   }
}

Your min array will be initialized with zero values. So the values in numbers will always be higher (assuming there are no negatives).

I'd suggest that you initialize min[j] with numbers[0] before the inner loop.

for (int j=0; j < 5; j++) //finds five highest
{
    min[j] = numbers[0]; // Add this line
    for (int i=0; i < numbers.length; i++)
        {

Try debugging your code by entering inside your nested min loop the following line:

System.out.println("the value of numbers[i] is: " + numbers[i]);

so it looks like this:

for (int j=0; j < 5; j++) //finds five lowest...array not assigned values
{
    for (int i=0; i < numbers.length; i++)
        {
            if (numbers[i] < min[j])
            {
                System.out.println("the value of numbers[i] is: " + numbers[i]);
                temp = numbers[i];
                numbers[i] = min[j];
                min[j] = temp;
            }
        }   
}

You'll notice something interesting. The innermost nested part doesn't even start.

Try putting that line into the nested max loop in its respective location instead... and it will run fine and show the max array values. You are getting zero values for the min array because (other than initial assigning) the innermost part of the nested min loop isn't being started somehow, so it fails to run and searched values do not get assigned to the min array.

The outer nested parts of the min loop run fine if you try debugging them with a similar line. It's this part that won't start and something's wrong with:

            if (numbers[i] < min[j])
            {
                System.out.println("the value of numbers[i] is: " + numbers[i]);
                temp = numbers[i];
                numbers[i] = min[j];
                min[j] = temp;
            }

(Update) In the min loop, numbers[i] from i=0 to i=4 have a value of 0 after completing the max loop.

You only need to add one line and use int i=5 instead of int i=0 inside your min loop:

for (int j=0; j < 5; j++) //finds five lowest...array not assigned values
{
    min[j] = max[4];                         // added line
    for (int i=5; i < numbers.length; i++)   // change to int i=5
    {
        if (numbers[i] < min[j])
        {...

Just curious , Cant you just sort it(using quick sort) select top five and bottom five ? - if you can use sorting I think this should work then

            int sum = 0;
    int count = 0;
    int[] max =  {Integer.MIN_VALUE,Integer.MIN_VALUE,Integer.MIN_VALUE,Integer.MIN_VALUE,Integer.MIN_VALUE};
    int[] min = {Integer.MAX_VALUE,Integer.MAX_VALUE,Integer.MAX_VALUE,Integer.MAX_VALUE,Integer.MAX_VALUE};
    int temp;
    int visited[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
    for (int j : numbers)// get sum
    {
        sum += j;
    }

    int tempindex;

    for (int j = 0; j < 5; j++) // finds five highest
    {

        for (int i = 0; i < numbers.length; i++) {
            if (visited[i] != 1) {
                if (numbers[i] > max[j]) {
                    max[j] = numbers[i];
                    tempindex = i;
                }
            }
        }
        visited[tempindex] = 1;
    }

    for (int j = 0; j < 5; j++) // finds five lowest...array not assigned
                                // values
    {
        for (int i = 0; i < numbers.length; i++) {
            if (visited[i] != 1) {
                if (numbers[i] < min[j]) {
                    min[j] = numbers[i];
                    tempindex = i;
                }
            }
        }
        visited[tempindex] = 1;
    }

As the other answer states, your problem is that you did not take into account the arrays beginning at 0. In Java, it sets default values for that data structure. For primitives, this will normally be 0 or false. However, when you move into data structures, you will have problems with null pointer exceptions if you fail to initialize your objects. For this reason, I would urge you to get into the habit of setting the values in your data structures before you ever use them. This will save you A LOT of debugging time in the future.


If you know the values in advance, you can set them manually with {0,0,0,0,0} notation, or your can initialize using a for loop:

for(int i = 0; i < array.length; i++)
array[i] = init_value;

I would recommend that you also look into trying to consolidate as much as possible. For example, in your code you go through the same data 4 times:

1) read the integers from the file into an integer array

2) sum all of the numbers in the integer array

3) look for max

4) look for min

I'm not sure if you've covered functions yet, but one example of consolidating this might look like:

while(fr2.hasNextInt()){
int i = fr2.nextInt();
sum += i;
checkHighest(i);
checkLowest(i);
}

You then define these functions and put the meat elsewhere. This lets you only worry about the loops in one place.

You have 2 problems. First was explained by Tom Elliott.

The second problem is that also the max[] array is initialized with 0, and when you search for max values you change the value from max array (which is 0) with the value from the numbers array, so the numbers array becomes filled with 0s.

A quick solve (though not the best) would be to copy the numbers array in a temp array and use that temp when searching for min values.

In case you didn't exactly understood what I said, try to make a print of the numbers array after you found the 5 max values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM