Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 正在尝试确定“中的array.length”;至于;使用变量时循环_Java_Arrays - Fatal编程技术网

Java 正在尝试确定“中的array.length”;至于;使用变量时循环

Java 正在尝试确定“中的array.length”;至于;使用变量时循环,java,arrays,Java,Arrays,我有一个名为“multiarray”的二维数组。第一个是[7],第二个当前初始化为[500]。我正在从一个文本文件中读取数据,该文件的第二个数组中有随机数目的条目。数组永远不会有500个条目,我需要知道有多少条条目 我在想y

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

我在想
y
会告诉我需要知道什么,但它似乎是循环的

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)
        {} 
     }
}
我已经为[x]准备了一个计数器,因为它是从文件中读入的,但我不希望在这里使用它,这样我就不必手动写出所有内容

输入文本文件的外观示例:

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

基本上,第一列是一周中的一天,第二列是一个温度。

这段代码没有太大的错误,但是如果用长度500初始化y数组,那么不管实际填充了多少个元素,长度都会返回这个值。如果需要,请在读取文件后初始化数组,或者使用java.util.List。如果值不可能是0,那么您也可以迭代所有非0值,并在第一个0处停止。

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

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

如果不想切换到ArrayList,则可以将数组更改为三维数组,第三维数组的长度为1。这可能是保持第二维度大小的地方

--

我不知道这是否是您的错误的原因,但您的代码中确实存在错误。最后的while循环尝试访问临时阵列外部:

int x = 0;
while (x < temp.length) {
    System.out.println(temp[x]);
    ++x;
    temp[x] = 0;
}
intx=0;
而(x<温度长度){
系统输出打印LN(温度[x]);
++x;
温度[x]=0;
}
这是从1到(temp.length+1)的循环,因为您的++x

改为使用for循环:

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

for(x=0;x现在我知道您的输入是什么样子了

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();
    }
  }
}
导入java.io.File;
导入java.io.FileNotFoundException;
导入java.util.ArrayList;
导入java.util.Scanner;
公共类道指{
公共静态void main(字符串[]args){
File File=新文件(“/Users/***/RandomInts.txt”);
试一试{
扫描仪=新扫描仪(文件);
ArrayList[]multiarray=new ArrayList[7];//这就是如何创建ArrayList的数组。
对于(int i=0;i

编辑:您添加的内容正确。我的不好。

使用ArrayList.ArrayList#size()我看不到您将任何内容放入数组中。我们需要查看您从文件中读取的代码,并将内容放入数组中。我会在这里使用所有答案,并使用ArrayList或LinkedList,但如果您确实必须使用基本数组,则可以使用
Integer
boxed类型。您只需计算所有数组中的非空整数以获取数据长度(数组长度仍将为500)。是的,好吧,这一切都错了。请在一分钟内检查我的编辑。我本来希望,尽管我已将其初始化为500。长度只会给我多少个元素(?)已添加。我将仔细查看arraylist,因为我需要对未知数量的条目进行此操作。我应该对该区域进行注释。我还没有调试到那个程度,我将重点关注“for”关于这一点的部分。我现在将编辑代码。这很好,它做了我需要它做的事情。我显然还有很多工作要做,但很欣赏解释代码的示例和注释。
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();
    }
  }
}