如何创建可以访问main中的变量而无需参数的方法JAVA
所以我在做一个程序,在一个文本文件中读取,计算学生成绩的平均值和标准差。如何创建两个使用main中的变量但不接受任何参数的方法。我在某个地方读到,Java中没有全局变量的概念,所以我不知道该怎么做。我设法创建了两个方法来实现这些功能,但将main中的变量作为参数,而不是代码中显示的参数,这不是我想要的。我会在我的课程中再上一节课吗如何创建可以访问main中的变量而无需参数的方法JAVA,java,class,methods,parameters,Java,Class,Methods,Parameters,所以我在做一个程序,在一个文本文件中读取,计算学生成绩的平均值和标准差。如何创建两个使用main中的变量但不接受任何参数的方法。我在某个地方读到,Java中没有全局变量的概念,所以我不知道该怎么做。我设法创建了两个方法来实现这些功能,但将main中的变量作为参数,而不是代码中显示的参数,这不是我想要的。我会在我的课程中再上一节课吗 import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner
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);
}
}
一个简单的解决方案是将scores数组移出main,使其成为类变量。因此,改变:
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];
try {
Scanner scanner = new Scanner(file);
...
致:
然后定义计算类内标准偏差和平均偏差的方法:
public void fndMean() {
Double sum = 0.0;
Double mean = 0.0;
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);
}
当然,您需要从main中调用fndMean。fndStanard也将是类似的 您可以从main和methods中获取要访问的静态变量。这些变量是类变量,在该类的所有对象之间共享 有一些东西类似于Java静态关键字,您可以在这种情况下使用它。如果您希望拥有一个变量,并且希望在不生成此类的任何对象的情况下访问该变量,则可以将其设置为静态。这意味着,尽管生成了一个类的许多对象,但静态变量只有一个实例。您还可以使用它来计算类的对象数。
静态变量也有问题,因此必须小心使用,因为它们不是线程安全的。如果不想从类中创建对象,可以使用静态变量。可以在类中使用静态变量。可以使用静态变量,但为什么需要没有参数的方法,而这些参数在编写代码时是有害的参数有什么问题?我如何创建两个方法,使用main中的变量,但不首先接受任何参数,告诉我们为什么?因为这听起来不是个好主意,我的意思是,这听起来是个糟糕的主意。您可以使用单例变量或类级静态变量。
public void fndMean() {
Double sum = 0.0;
Double mean = 0.0;
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);
}