我尝试使用两种方法将程序写入文件。它编译时没有错误,但是当它写入的文件打开时,只打印带有(0,0)的坐标。它应该从数组中打印10000随机协调。为什么它只打印出(0,0)坐标?我也把退货声明放在正确的位置吗?
import java.io.*;
public class program
{
public static void main (String [] args) throws IOException
{
int points = 10000, dimension = 2, lengthA = 100;//int variables are declared and initialized
PrintWriter fileOut = new PrintWriter (new FileWriter ("arrayPoints.txt"));
double length [] = new double [dimension];//array for length is declared
double coordinate [][] = new double [points][dimension];//coordinate array is declared
for (int i = 0; i < points; i++){
fileOut.println(java.util.Arrays.toString(coordinate[i]));
}
fileOut.close();//writes to file
}//end main method
public static double writeTofile (double length[], double coordinate[][], int points, int dimension, int lengthA)
{
int x = 0, y = 0;
for(int z = 0; z < dimension; z++){//fills the length array with the the set value of lengthA
length[z] = lengthA;
}
for(x = 0; x < points; x++){//runs 1000 times to print 1000 data points
for (y = 0; y < dimension; y++){//runs 2 times to print an x and y coordinate
coordinate [x][y]= (2 *Math.random() - 1) * length[y];// finds a random number in the range and assiigns it to the coordinate array
}//end for
}//end for
return coordinate[x][y];
}//main method
}//program
我已经更改了我的代码并进行了编译。但是当你看到它打印到的文件时,会看到随机字母([D @ 76f1fad1 [D @ 889ec59 ...])。为什么会这样?
import java.io.*;
public class program
{
public static void main (String [] args) throws IOException
{
int points = 10000, dimension = 2, lengthA = 100;//int variables are declared and initialized
PrintWriter fileOut = new PrintWriter (new FileWriter ("arrayPoints.txt"));
double length [] = new double [dimension];//array for length is declared
double coordinate [][] = new double [points][dimension];//coordinate array is declared
writeTofile(length, coordinate, points, dimension, lengthA);
for (int i = 0; i < points; i++){
fileOut.println(Arrays.toString(coordinate[i]));
}
fileOut.close();//writes to file
}//end main method
public static void writeTofile (double length[], double coordinate[][], int points, int dimension, int lengthA)
{
int x = 0, y = 0;
for(int z = 0; z < dimension; z++){//fills the length array with the the set value of lengthA
length[z] = lengthA;
}
for(x = 0; x < points; x++){//runs 1000 times to print 1000 data points
for (y = 0; y < dimension; y++){//runs 2 times to print an x and y coordinate
coordinate [x][y]= (2 *Math.random() - 1) * length[y];// finds a random number in the range and assiigns it to the coordinate array
}//end for
}//end for
}//main method
}//program
答案 0 :(得分:3)
您没有使用main
方法中的值调用填充坐标数组的方法。
您可以将其命名为:
...
double coordinate [][] = new double [points][dimension];//coordinate array is declared
writeTofile(length, coordinate, points, dimension, lengthA)
for (int i = 0; i < points; i++){
...
至于return语句,它位于正确的位置,但它将抛出ArrayIndexOutOfBoundsException
,因为它正在访问数组中不存在的偏移量。您想要一个返回值,您对它有什么用处?