【发布时间】:2017-01-13 23:14:49
【问题描述】:
所以我正在开发一个读取文本文件的程序来计算学生分数的平均值和标准差。我将如何创建两个使用 main 中的变量但不接受任何参数的方法。我在某处读到Java中没有全局变量的概念,所以我很困惑如何做到这一点。我设法创建了两种方法来执行这些操作,但是将 main 中的变量作为参数(未在我的代码中显示),这不是我想要的。我的计划中会再开一门课吗?
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ScannerReadFileSplit {
public static void main(String[] args) {
File file = new File("NamesScore.txt");
String[] names = new String[5];
Double[] scores = new Double[5];
int i = 0;
Double sum = 0.0;
Double mean = 0.0;
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String [] words = line.split("\t");
names[i] = words[0];
scores[i] = Double.parseDouble(words[1]);
i++;
}
for(int k=0; k < names.length; k++) {
System.out.printf("%d: %s\n", k, names[k]);
}
System.out.println();
for(int a = 0; a < scores.length; a++) {
System.out.printf("%d: %.1f\n", a, scores[a]);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//Make this a method called fndMean() using the scores array
for(int j = 0; j < scores.length; j++) {
sum += scores[j];
}
mean = (sum/(scores.length));
System.out.printf("The mean of the scores is: %.1f\n", mean);
//Make this a method called fndStandard() using the scores array
double sd = 0;
for(int x = 0; x < scores.length; x++) {
sd += ((scores[x] - mean) *(scores[x] - mean)) / (scores.length - 1);
}
double standardDeviation = Math.sqrt(sd);
System.out.printf("The standard deviation is: %.2f\n", standardDeviation);
}
}
【问题讨论】:
-
你可以在类上使用静态变量。
-
你可以用静态的,但是为什么你需要没有参数的方法,当你的代码增长时会很糟糕。
-
参数有什么问题?
-
我将如何创建两个使用 main 中的变量但不接受任何参数的方法 首先,告诉我们为什么?因为这听起来不是一个好主意(我的意思是,这听起来像是一个可怕的主意)。您可以使用
Singleton或class级别变量 (static)。
标签: java class methods parameters