プログラムをメソッドに分割する際に問題が発生します (具体的には、メイン メソッドと、すべての計算を行う別のメソッドなど)。既存のコードを分割して新しいメソッドを作成する適切な方法がわかりません。私のプログラムもファイルに書き込みます。
コードをコンパイルすると、次のエラーが表示されます
ファイル: F:\COMPSCI 12\java1.java [行: 37] エラー: F:\COMPSCI 12\java1.java:37: return ステートメントがありません
しかし、私はすでにリターンステートメントを持っています。
メソッドを適切に使用しましたか?それとも何が悪いのですか?ありがとう
メソッドのない元のコード
import java.io.*;
public class java1
{
public static void main (String [] args) throws IOException
{
//int variables are declared
int numpoints = 100, dimension = 2, length = 100;//numpoints is set to 100, dimension is set to 2, length is set to 100
PrintWriter fileOut = new PrintWriter (new FileWriter ("arrayNumPoints.txt"));
//arays are declared/initialized
double [] lengthscale = new double [dimension];
double [][] locations = new double [numpoints][dimension];
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 it
fileOut.println( locations[x][y] + ", ");//prints out coordinate
}//end nested for loop
}//end for loop
fileOut.close ();
}//end main method
}//end cass
同じコードだがメソッドを使用
import java.io.*;
public class J4_2_MultiDimensionalArray7
{
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[m]) + ", ");
}
}//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 it
return locations[x][y];//returns the value of locations
}//end nested for loop
}//end for loop
fileOut.close ();//close file
}//end writefile methos
}//end cass