package com.mohamadibrah;
import java.util.Scanner;
public class Main {
private static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
System.out.println(returnAverage(printNumbers(enterNumbers()))); // 10
}
public static double returnAverage(double[] array){
double result=0;
for(int i=0;i<array.length;i++) {
result += array[i];
}
System.out.println("the average is:");
return (double)result/(array.length);
}
public static double[] enterNumbers(){
System.out.println("please enter the number of values:");
int sca = sc.nextInt();
double[] myAverage = new double[sca];
System.out.println("please enter the numbers:");
for(int i=0;i<myAverage.length;i++){
double input = sc.nextDouble();
myAverage[i] = input;
}
return myAverage;
}
public static double[] printNumbers(double[] array1){
System.out.println("your numbers are:");
double[] array2 = new double[array1.length];
for(int i=0;i<array2.length;i++) {
System.out.println("the number "+i+" is:"+array1[i]);
array2[i] = array1[i];
}
return array2;
}
}
&#34; 10&#34;在评论中
如果一切正常,将多个方法堆叠在一起是否很好?或者最好尽可能地将它们分开
答案 0 :(得分:1)
此处的问题是可调试性和可读性。
<强>调试性强>:
当您调试这样的代码时,检查每个内部方法返回值会非常棘手。
<强>可读性强>:
由于难以理解,因为读者需要从内到外读取代码,您错过了为保存内部方法返回值的变量赋予有意义名称的机会,从而向读者解释了什么它是。
考虑以下备选代码,并牢记以上几点:
List<Double> userChosenNumbers = enterNumbers();
Double average = returnAverage(userChosenNumbers);
System.out.println(average);