2013-09-23 46 views
0

當我運行我的程序,將其寫入文件,但是隻寫第一個座標:寫入文件的Java

[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], 

其餘的都是[0.0。 0.0]它應該是由程序生成的一些其他隨機數。

這是爲什麼?該程序是將程序生成的座標寫入另一個文件。 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 

回答

1

這是一個調試器會有所幫助。

它會告訴你,你有你的循環內的回報,你的第一個位置[X] [Y]設置後返回。因爲不需要return語句,所以我建議你嘗試一下你的調試器,因爲它旨在幫助你發現錯誤。

+1

'writeToFile()'中的'return'語句甚至不是必需的,因爲無論如何'locations'都會被數據填充。 –

+0

@peter Lawrey當我在while循環之外移動return語句時,出現錯誤,指出找不到x和y。是否因爲x和y在循環內聲明而return語句在外? – user101

+0

@ user101你是對的,musical_coder也是正確的,你不需要它,所以刪除它。 –