尝试在使用变量时在“for”循环中确定array.length

时间:2013-11-23 04:15:19

标签: java arrays

我有一个名为“multiarray”的二维数组。第一个是[7],第二个是当前初始化为[500]。我正在从一个文本文件中读取,该文件随机数量的条目将转到第二个数组。该数组永远不会有500个条目,我需要知道有多少条目。

我在想y < multiarray[x].length会告诉我我需要知道什么,但它似乎在循环。

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Formatter;
import java.util.Scanner;

public class DOW 
{
    public static void main(String[] args) 
    {
        File file = new File ("/Users/***/RandomInts.txt") ;
        try
        {
        Scanner scanner = new Scanner(file) ;
        //Formatter formatter = new Formatter (new File ("outputfile.txt")) ;

        int [][] multiarray = new int [7][500];

        int counter1 = 0; 
        int counter2 = 0; 
        int counter3 = 0; 
        int counter4 = 0;
        int counter5 = 0;
        int counter6 = 0; 
        int counter7 = 0;

          while (scanner.hasNext())
            {
                int dow = scanner.nextInt () ;
                int temp = scanner.nextInt () ;
                dow = dow -1;

                if(dow == 0)
                {
                    multiarray[dow][counter1] = temp;
                    counter1 ++;
                }

                if(dow == 1)
                {
                    multiarray[dow][counter2] = temp;
                    counter2 ++;
                }

                if(dow == 2)
                {
                    multiarray[dow][counter3] = temp;
                    counter3 ++;
                }

                if(dow == 3)
                {
                    multiarray[dow][counter4] = temp;
                    counter4 ++;
                }

                if(dow == 4)
                {
                    multiarray[dow][counter5] = temp;
                    counter5 ++;
                }

                if(dow == 5)
                {
                    multiarray[dow][counter6] = temp;
                    counter6 ++;
                }

                if(dow == 6)
                {
                    multiarray[dow][counter7] = temp;
                    counter7 ++;
                }
            }

            for (int x = 0; x < 7; x++)
                {
                    int hightemp = 0;
                    int lowtemp = 0;
                    int avetemp = 0;

                    for (int y = 0; y < multiarray[x].length ; y++)
                    {
                        if (multiarray[x][y] > hightemp)
                        {
                            hightemp = multiarray[x][y];
                        }

                        if (multiarray[x][y] < lowtemp)
                        {
                            lowtemp = multiarray[x][y];
                        }

                        avetemp = avetemp + multiarray[x][y];
                    }
                    //avetemp = avetemp /    
                }

            //formatter.format (" %d %d \n " , dow , temp ) ;

            //formatter.flush () ;
            //formatter.close () ;

            //int[] dow;
            //dow = new int [7];

            //int[] temp;
            //temp = new int [100];

            //int x = 0;
            //while ( x < temp.length)
            //{
                //System.out.println (temp[x]);
                //++x;
                //temp[x]=0;
            //}
    }         

        catch (FileNotFoundException e)
        {} 
     }
}

我想知道数组长度的原因是因为我想在数学中调用数字。

avetemp = avetemp / multiarray[x].length

我已经为[x]提供了一个计数器,因为它正在从文件读入,但我希望不要在这里使用它,这样我就不必手动写出所有内容。

输入文本文件的示例:

5 67
2 -15 
1 -40 
7 32 
6 -24 
7 33 
5 -32 
3 57 
3 41 
6 51 

基本上第一列是星期几,第二列是温度。

4 个答案:

答案 0 :(得分:1)

现在我知道你的输入是什么样了。

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;

public class DOW {

  public static void main(String[] args) {
    File file = new File("/Users/***/RandomInts.txt");
    try {
      Scanner scanner = new Scanner(file);

      ArrayList<Integer>[] multiarray = new ArrayList[7]; // This is how one would make an array of ArrayList's.
      for (int i = 0; i < multiarray.length; i++)
        multiarray[i] = new ArrayList<Integer>();

      while (scanner.hasNextInt()) { //This is how you would save the values. You were saving temperatures incorrectly.
        int dow = scanner.nextInt() - 1; //Get day of week.
        int temp = scanner.nextInt(); //Get temperature. [Would throw exception here if your input was bad]
        multiarray[dow].add(temp); //Store temperature in the array representing the day of week.
      }

      // Looks like you want to find min, max and average in each column here.
      for (int x = 0; x < 7; x++) {
        int hightemp = Integer.MIN_VALUE; // Set this to something really low. (You will see why in a minute)
        int lowtemp = Integer.MAX_VALUE; // Set this to something really high.
        double avetemp = 0; // You seem to be using ave as "sum" right now and then you plan on dividing which is fine. This should also be a double.
        int size = multiarray[x].size(); // No point calling .size() [or in general any function] over and over again. Its better to just cache the answer.
        for (int y = 0; y < size; y++) {
          int num = multiarray[x].get(y); // Same logic as size here.
          hightemp = Math.max(hightemp, num);
          lowtemp = Math.min(lowtemp, num);
          avetemp += num;
        }
        avetemp = avetemp / size;
        // P.S.: Also you probably want to save the values of hightemp, lowtemp, avetemp somewhere after doing all this work!
        // Removed the rest of your code as it is irrelevant for your question.
      }
      // Close your streams.
      scanner.close();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (Exception e) {
      // This would happen if your input file is bad.
      e.printStackTrace();
    }
  }
}

编辑:您正在正确添加内容。我的坏。

答案 1 :(得分:0)

此代码没有太大问题,但是如果初始化长度为500的y数组,则无论实际填充了多少元素,都将返回长度。如果需要,请在读取文件后初始化数组,或使用java.util.List。如果值不可能为0,那么您也可以迭代所有非0值,并在第0位停止。

答案 2 :(得分:0)

java中的数组是静态的,这意味着已预先分配了您声明的空间,因此,无论您实际插入多少条目,多数组[y] .length将始终为500.您可以使用ArrayList或者是LinkedList而已.Their空间全部动态分配,因此它们的长度将告诉你它们实际包含的条目数。

答案 3 :(得分:0)

数组具有固定大小 - 您将第二个维度的数组初始化为500.在该数组上调用长度将始终返回500.如果您需要更动态的数据结构,请考虑使用ArrayList。当你添加它时,size()返回的值将递增。

如果您不想切换到ArrayList,则可以将数组更改为三维数组,第三个维度的长度为1.这可能是您维护第二维的大小的位置。

-

我不知道这是否会导致您的错误,但您的代码中确实存在错误。最后的while循环尝试访问临时数组外部:

int x = 0;
while (x < temp.length) {
    System.out.println(temp[x]);
    ++x;
    temp[x] = 0;
}

由于你的++ x,它从1循环到(temp.length + 1)。

改为使用for循环:

for(x=0; x<temp.length; x++)
{
    System.out.println(temp[x]);
    temp[x] = 0;
}