简体   繁体   English

在Java中填充双向数组

[英]filling an bidimensionnal array in java

I'm having some issues filling a bidimensionnal double-array out of a multi-dimensional object-array. 我在从多维对象数组填充双向双数组时遇到一些问题。 My problem is that null value are causing a java.lang.NullPointerException at IOControl.ReadCSV$1.compare(ReadCSV.java:328) at IOControl.ReadCSV$1.compare(ReadCSV.java:1) at java.util.TimSort.countRunAndMakeAscending(Unknown Source) at java.util.TimSort.sort(Unknown Source) at java.util.TimSort.sort(Unknown Source) at java.util.Arrays.sort(Unknown Source) at IOControl.ReadCSV.run(ReadCSV.java:324) at en.window.Main.main(Main.java:46) , and i really don't understand why. 我的问题是空值导致java.lang.NullPointerException at IOControl.ReadCSV$1.compare(ReadCSV.java:328) at IOControl.ReadCSV$1.compare(ReadCSV.java:1) at java.util.TimSort.countRunAndMakeAscending(Unknown Source) at java.util.TimSort.sort(Unknown Source) at java.util.TimSort.sort(Unknown Source) at java.util.Arrays.sort(Unknown Source) at IOControl.ReadCSV.run(ReadCSV.java:324) at en.window.Main.main(Main.java:46)java.lang.NullPointerException at IOControl.ReadCSV$1.compare(ReadCSV.java:328) at IOControl.ReadCSV$1.compare(ReadCSV.java:1) at java.util.TimSort.countRunAndMakeAscending(Unknown Source) at java.util.TimSort.sort(Unknown Source) at java.util.TimSort.sort(Unknown Source) at java.util.Arrays.sort(Unknown Source) at IOControl.ReadCSV.run(ReadCSV.java:324) at en.window.Main.main(Main.java:46) ,我真的不明白为什么。

What am i doing ? 我在做什么 ? I'm reading a CSV - file, i'm storing the input line by line, in my array of object Data called content . 我正在读取CSV文件,将输入的内容逐行存储在名为content的对象Data数组中。 Then i'm filling a double bidimensional array called sortedOutput in which i would like to store LeftSpeed and NormAvgPowOutput which are double value stored in my Data array. 那么我填补了double称为二维数组sortedOutput中,我想用来存储LeftSpeedNormAvgPowOutput是存储在我的双值Data阵列。

What i want : To have my sortedOutput bidimensionnal array sorted from the smallest to the biggest value on dimension 0 : for variable LeftSpeed . 我想要的是:将我的sortedOutput数组从维度0的最小值到最大值进行排序:对于变量LeftSpeed

So how can i avoid the null values? 那么如何避免空值呢? Because when i try to spot them while filling my second array, the compilator says i can't compare a double to a null value. 因为当我尝试在填充第二个数组时发现它们时,编译器说我无法将double值与null值进行比较。

Sorry for the long post, hope you guys can help me out :) Here my code : 对不起,很长的帖子,希望你们能帮助我:)这是我的代码:

public void run(String path, int length) 
{
/* 
* Main function of ReadCSV class.
 * Open / reads / closes the file.
 * Fills the object.
 */

  BufferedReader br = null;
  String input = "";
  String cvsSplitBy = ",";
  int[] pos = new int[200];

  Data[] content = new Data[length];
  Double[][] sortedOutput = new Double[length][4];
  int i = 0;
  int j = 0;
  int k = 0;

  try 
  {
    br = new BufferedReader(new FileReader(path));
    while ((input = br.readLine()) != null) 
     {
       // use comma as separator
       String[] lines = input.split(cvsSplitBy);
       content[i] = new Data(); 
       if (i == 0)
       {
         //not relevant here                
       }
       else
       {
        j = 0;
        content[i].setTime("TIME", getTime(pos[j++], lines));
        content[i].setData("DATA", getContent(pos[j++], lines));
        //etc
       }
       // gets rid of non coherent or useless values, e.g negative power, ...
       if (content[i].lhWdStdev > 0 && content[i].rhWdStdev > 0)
       {
        normalizeData(content[i]); // not relevant
        content[k].setLeftSpeed();
        sortedOutput[k][0] = content[k].getLeftSpeed();
        sortedOutput[k][2] = content[k].getNormAvgPowOutput();
        Arrays.sort(sortedOutput, new java.util.Comparator<Double[]>()
        {
           public int compare(Double[]a, Double[]b)
           {
             return Double.compare(a[0], b[0]);
            }
         });
   }
   if (sortedOutput[k][0] == null)
   {
     System.out.println("FAIL");
   }
   System.out.println("Output = " +sortedOutput[k][0]);
   i++;
   k++;
 }
} 
catch (FileNotFoundException e) 
  {
    e.printStackTrace();
  } 
catch (IOException e) 
  {
    e.printStackTrace();
  } 
finally 
  {
  // Again it's not relevant
}

EDIT : So finally i made 2 huge misstakes. 编辑:所以最后我犯了两个巨大的错误。 First i tried to sort the array in the loop, that means BEFORE it was fully filled (thanks @Ted Hopp). 首先,我尝试在循环中对数组进行排序,这意味着在数组完全填充之前(感谢@Ted Hopp)。 Secondly i didn't handle the null values correctly. 其次,我没有正确处理null值。 I should have checked if ( a != null , b != null , a[0] != null , b[0] != null ) and then return the new order. 我应该检查( a != nullb != nulla[0] != nullb[0] != null ),然后返回新顺序。 (thanks @jboi ). (感谢@jboi)。

You are crashing because you are sorting the array sortedOutput before you have read all the entries. 之所以崩溃,是因为您在读取所有条目之前对数组sortedOutput进行了排序。 The call to Arrays.sort() should be moved to past the loop where you are reading the input. Arrays.sort()的调用应移至读取输入的循环Arrays.sort()

Alternatively, you can call Arrays.sort() with an expanded argument list to control how much of the array is sorted: 另外,您可以使用扩展的参数列表调用Arrays.sort()来控制对数组进行排序的数量:

Arrays.sort(sortedOutput, 0, k + 1, new java.util.Comparator<Double[]>()
    {
       public int compare(Double[]a, Double[]b)
       {
         return Double.compare(a[0], b[0]);
        }
     });

However, I see no reason to constantly be sorting after each input. 但是,我认为没有理由在每次输入后不断进行排序。

You also oddly have the check against array elements being null coming after the call to Arrays.sort() which requires them to not be null . 您还奇怪地在调用Arrays.sort()要求检查数组元素是否为null ,这要求它们不为null If you use the second option, you at least need to move the error checks to before the sort. 如果使用第二个选项,则至少需要将错误检查移至排序之前。

As a third alternative, you could explicitly allow for a null array entry inside your comparator. 作为第三种选择,您可以在比较器中明确允许使用null数组条目。 All null entries should sort the same and should always be either before or after non- null entries. 所有null条目应排序相同,并且应始终在非null条目之前或之后。

What I see from the stacktace is, that the command Double.compare(a[0], b[0]); 我从堆栈中看到的是命令Double.compare(a[0], b[0]); is causing the NullPointerException. 导致NullPointerException。 That means, that one the two is null . 这意味着,两者之一为null What you can to as a quick solution is to change the command with: 作为快速解决方案,您可以使用以下命令来更改命令:

Double.compare((a[0]==null)? Double.NaN:a[0], (b[0]==null)? Double.NaN:b[0]);

This can only be quick and dirty as you need to understand WHY there're null, what is in the CSV File, that makes them null and how you handle such data. 这只是快速而又肮脏,因为您需要了解为什么会出现空值,CSV文件中的内容,使它们为空以及如何处理此类数据的情况。

So first of all, finally clause is relevant here : you need to invoke the close() method of your stream br there, to avoid any resource leak in case of exceptions. 因此,首先,finally子句在这里是相关的:您需要在此处调用流的close()方法,以避免在发生异常的情况下发生任何资源泄漏。

Secondly, I see no advantage of using arrays instead of list here. 其次,我看不到使用数组而不是列表的优势。 In java, we use lists (especially ArrayList in this case) over arrays. 在Java中,我们在数组上使用列表(在这种情况下,尤其是ArrayList)。 Arrays are seldom used, not like in C. Perfs are quite the same (providing you init your list with the same size as you do with your array). 很少使用数组,这与C语言中的情况不同。Perfs完全相同(假设您使用与数组相同的大小来初始化列表)。 Lists are better, because they give you better compile-time check, whereas Arrays only gives runtime-check. 列表更好,因为它们可以为您提供更好的编译时检查,而数组仅提供运行时检查。 For example, the following code compiles without errors: 例如,以下代码可正确编译:

String[] strings = new String[1];
Object[] objects = strings;
objects[0] = new Integer(1); 

Thirdly, when you have an exception, it is critical that you post here the FULL stacktrace. 第三,当您遇到异常时,至关重要的是在此处发布FULL堆栈跟踪。 People will give you better help if they have better information! 如果人们有更好的信息,他们将为您提供更好的帮助!

Fortunately, here, I can see where the NPE is thrown: Double.compare takes two double as arguments (and not Double). 幸运的是,在这里,我可以看到NPE的抛出位置:Double.compare将两个double用作参数(而不是Double)。 Therefore, your Double are autoboxed to double (google "java autoboxing"), throwing a NPE if they are null. 因此,您的Double会自动装箱以加倍(google“ java autoboxing”),如果它们为null,则会抛出NPE。 You need to handle the 3 cases of nullity (one is null, the other, and both of them) in your comparator. 您需要在比较器中处理3种无效情况(一种为null,另一种为两者)。 Alternatively, you can remove null values before sorting. 或者,您可以在排序之前删除空值。

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

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