2013-09-23 2 views
0

У меня возникают проблемы с делением моей программы на методы (в частности, основной метод и другой метод, который выполняет все вычисления и т. Д.). Я не уверен в правильном способе разделить мой существующий код, чтобы создать новый метод. Моя программа также записывает в файл.Использование методов в java-программе

Когда я компиляции кода я получаю сообщение об ошибке говорящее

File: F:\COMPSCI 12\java1.java [line: 37] Error: F:\COMPSCI 12\java1.java:37: missing return statement

Но у меня уже есть оператор возврата.

Я правильно использовал методы? Или что не так? Благодаря

исходный код без методов

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 
+1

Необходимо указать значения возврата для каждого возможного пути, который может принимать код – porfiriopartida

ответ

4

Предположим, что numpoints == 0. Ваш код когда-либо достигнет заявления о возврате?

В другом случае, если ваша функция делает возвращение, будет ли fileOut.close(); когда-либо называться?

Java признает, что существует случай, когда оператор возврата может быть не достигнут, и действует так, как будто у вас его нет. Чтобы исправить это, вы должны иметь оператор возврата «по умолчанию» в конце функции, чтобы обрабатывать край, где ваши петли не вводятся.

Im not sure on the proper way to divide up my existing code to create a new method.

Это действительно до вас и то, что делает код, но несколько рекомендаций:

  • Способ получения слишком долго, чтобы понять? Разбейте его на несколько методов.
  • Вы пишете «дублирующий код»? Может быть, это должно пойти в методе.
  • Такие вещи, как запись в файл, являются дискретной единицей операции. Другими словами, отдельно от логики остальной части вашей программы. Поэтому его следует разделить как собственный метод.
  • Etc.
0

Метод является неправильным. Вы указали возвращаемое значение как Double, однако вы пытаетесь вернуть массив парных чисел. Плюс оператор return будет вызываться во время первой итерации циклов, поэтому он остановится там.

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

    for (int x=0; x < numpoints; x++){ 
     for (int y=0; y < dimension; y++){ 
     locations [x][y]= (2 * Math.random() - 1) * lengthscale[y]; 

     return locations[x][y]; <------------ this would be called in the first iteration; 
     }//end nested for loop 

    }//end for loop 

    fileOut.close();//close file 
    } 
0

Остальные ребята указали несколько вещей.

Я думаю, что наиболее важным общим принципом является separation of concerns. В вашем конкретном случае вычисление чего-то в одном месте и сохранение данных в файле - две разные, четко выраженные проблемы.

Смежные вопросы