【问题标题】:Program compiles but doesn't write to file correctly程序编译但未正确写入文件
【发布时间】:2013-09-23 21:48:37
【问题描述】:

程序可以编译,但是当它写入文件时会出现以下情况:

[[D@92ca580, [D@52257b34, [D@1abbbd0e, [D@1b78efd8.....而且还在继续

我的代码有什么问题?我的结构是否正确? 还有在main方法中调用writefile方法的时候,我做对了吗?

更新** 我把它修好了,现在文件上出现了这个:

[[0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0]...

我认为问题在于我没有直接调用 writefile 方法。这是为什么呢?我该如何解决?

 import java.io.*;

public class j4 {
  public static void main (String [] args) throws IOException
  {
    int numpoints = 100, dimension = 2, length = 100;//numpoints is set to 100, dimension is set to 2, length is set to 100

    //arrays are initializewd and declared
    double [] lengthscale = new double [dimension];
    double [][] locations = new double [numpoints][dimension];

    PrintWriter fileOut = new PrintWriter (new FileWriter ("arrayNumPoints.txt"));

    for(int m=0; m <length; m++){//for loop
      fileOut.println(java.util.Arrays.toString(locations) + ", ");//writes to file
    }
    fileOut.close ();//close file

  }//end main

  public static Double writefile(Double locations[][], Double lengthscale[], int dimension, int numpoints, Double length)throws IOException
  {

    for (int a = 0; a < dimension; a++){//for loop runs while a is less than dimension
      lengthscale[a] = length;//stores array
    }//end for loop

    for (int x=0; x < numpoints; x++){//for loop runs while x is less than numpoints
      for (int y=0; y < dimension; y++){//nested for loop runs while y is less than dimension
        locations [x][y]= (2 * Math.random() - 1) * lengthscale[y];//creates the range and choses random point within 
          return locations[x][y];

      }//end nested for loop
    }//end for loop

    //if program doesnt run through loop.. alternative return statement (but
     double b= 1;    
     return b;
  }//end writefile methos
}//end class

【问题讨论】:

  • 如果您描述了您的程序应该做什么,这将很有帮助。
  • 这是数组的#toString()。我想你需要字符串内容,你需要遍历嵌套数组。
  • @qqilihq 嗨!你是什​​么意思你需要字符串的内容并遍历嵌套数组?我是初学者,所以我有点困惑
  • 你有一个二维数组,Arrays#toString 只迭代顶部数组,并简单地给出每个包含数组 toString() 的结果(这会给你类似[D@92ca580 的结果,如你的例子)。在下面查看 micha 关于Arrays.deepToString() 的回答(比我上面建议的迭代要好)。
  • @qqilihq 好的,谢谢!

标签: java methods return writetofile


【解决方案1】:

Arrays.toString() 只会为您的 first 数组创建一个字符串。 locations 是一个多维数组(数组值包含另一个数组)。

你应该改用Arrays.deepToString()

返回一个字符串表示的“深层内容” 指定的数组。如果数组包含其他数组作为元素,则 字符串表示包含它们的内容等等。这种方法 专为将多维数组转换为字符串而设计。

【讨论】:

    【解决方案2】:

    尝试改用Arrays.deepToString,这样

    返回一个字符串表示的“深层内容” 指定的数组。如果数组包含其他数组作为元素,则 字符串表示包含它们的内容等等。 这个方法 专为将多维数组转换为字符串而设计

    但是,假设您不希望以特定格式打印数字。在这种情况下,您可能只能选择循环遍历元素并以所需的格式打印它们。

    在我看来,上述方法对于记录/调试操作相当有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-28
      • 2020-01-29
      • 1970-01-01
      相关资源
      最近更新 更多