简体   繁体   English

无法在数组中找到五个最低值...最大值在min数组未分配值时有效

[英]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. 我想出了如何找到五个最高值,但我找到最低值的min数组总是输出五个0。

Output: //obviously dependent on individual text file 输出://显然依赖于单个文本文件

Total amount of numbers in text file is 10 文本文件中的总数量为10

Sum is: 1832 总和是:1832年

1775 14 9 9 7 //max 1775 14 9 9 7 //最大

0 0 0 0 0 //min 0 0 0 0 0 //分钟

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. 您的min数组将初始化为零值。 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. 我建议你在内循环之前用数字[0]初始化min [j]。

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: 尝试通过在嵌套的min循环中输入以下行来调试代码:

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. 你得到min数组的零值,因为(除了初始赋值)嵌套的min循环的最里面的部分没有以某种方式启动,所以它无法运行,并且搜索的值不会被分配给min数组。

The outer nested parts of the min loop run fine if you try debugging them with a similar line. 如果您尝试使用类似的行调试它们,则min循环的外部嵌套部分可以正常运行。 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. (更新)在最小循环中,在完成最大循环后,从i = 0到i = 4的数字[i]的值为0。

You only need to add one line and use int i=5 instead of int i=0 inside your min loop: 你只需要添加一行并在你的min循环中使用int i = 5而不是int i = 0:

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. 正如另一个答案所述,您的问题是您没有考虑从0开始的数组。在Java中,它为该数据结构设置默认值。 For primitives, this will normally be 0 or false. 对于基元,通常为0或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: 如果您事先知道这些值,可以使用{0,0,0,0,0}表示法手动设置它们,或者使用for循环初始化:

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: 例如,在您的代码中,您将浏览相同的数据4次:

1) read the integers from the file into an integer array 1)将文件中的整数读入整数数组

2) sum all of the numbers in the integer array 2)求和整数数组中的所有数字

3) look for max 3)寻找最大值

4) look for min 4)寻找分钟

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. 你有2个问题。 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. 第二个问题是max []数组也初始化为0,当你搜索最大值时,你用数字数组中的值更改max array(即0)的值,所以数字数组变为0。

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. 如果您没有完全理解我所说的内容,请在找到5个最大值后尝试打印数字数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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