简体   繁体   English

写入文件java

[英]writing to a file java

When i run my program, it writes to a file but it only writes the first coordinate: 当我运行程序时,它会写入文件,但只会写入第一个坐标:

[79.93768569366277, 0.0], 
    [0.0, 0.0], 
    [0.0, 0.0], 
    [0.0, 0.0], 
    [0.0, 0.0], 
    [0.0, 0.0], 
    [0.0, 0.0], 
    [0.0, 0.0], 
    [0.0, 0.0], 
    [0.0, 0.0], 
    [0.0, 0.0], 
    [0.0, 0.0], 

The rest are [0.0. 其余为[0.0。 0.0] where it should be some other random numbers generated by the program. 0.0],它应该是程序生成的其他一些随机数。

Why is that? 这是为什么? The program is to write the coordinates generated by the program to another file. 该程序是将程序生成的坐标写入另一个文件。 CODE: 码:

 import java.io.*;
    import java.util.Arrays;

    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"));

         writefile(lengthscale, locations, dimension, numpoints, length);


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

      }//end main

      public static Double writefile(double lengthscale[], double locations[][], int dimension, int numpoints, int 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 cass

This is where a debugger would help. 这是调试器将提供帮助的地方。

It would show you that you have a return inside your loop and you return after the very first location[x][y] is set. 它会告诉您循环内有返回值,并且在设置了第一个位置[x] [y]之后返回。 Remove the return statement as it is not needed, and I suggest you try your debugger as it is designed to help you find bugs. 删除return语句,因为它不是必需的,我建议您尝试使用调试器,因为它旨在帮助您查找错误。

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

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