如何从方法中声明一个 private static final int(java 初学者)

How to declare a private static final int from a method (java beginner)

首先要做的事情...我是 java 的新手,最近才开始尝试使用 multi-class 和 multi-method 代码。

所以,我有一个我必须编写的程序,它在 class(从外部文件读取)中获取学生的成绩,然后计算每个学生的最终成绩。我目前正在编写确定 class 中有多少学生的代码。这涉及计算外部文件中的行数。

这是我目前所拥有的...

 import java.io.*;
 import java.util.Scanner;

 public class Student
 {
 // instance variables 
private int Quiz1;
private int Quiz2;
private int MidTerm;
private int Final;
private int FinalP;
private int LetterGrade;


public Student(int q1, int q2, int mt, int f)
{
   Quiz1 = q1;
   Quiz2 = q2;
   MidTerm = mt;
   Final = f;
}

public int getStudentNumber()
{
   Scanner two = null;
    try 
   {
      // Create a scanner to read the file, file name is parameter
       two = new Scanner (new File("Prog349f.txt"));
      } 
    catch (FileNotFoundException e) 
    {
    System.out.println ("File not found!");
    // Stop program if no file found
    System.exit (0);
    } 

   int lines = 0;   
    while(two.hasNext()) 
    {    
    lines++;
    two.nextLine();
   }
   two.close();
   return(lines);  
 }  
}

我已经决定要将学生人数lines/number保存为private static final int,(目前的class化只是一个占位符)。我只是不太确定如何保存它。在所有示例中,private static final(s) 声明如下:

 private static final double PI = 3.14; 

tldr; 我非常确定这已经被讨论过很多次了,但是使用方法定义 public static final 的协议是什么?

您误解了 static final 的用途,它仅适用于可以在加载 class 时设置值并且之后永远不会更改的情况。它对于声明常量(如您的示例中的 PI)很有用,您可以在程序运行之前知道它应该包含什么。

相反,对于您读入的每一行,创建一个 Student 并将其添加到列表中。每当你想要学生的数量时,你可以在列表中调用 size 方法。

如果您真的执着于将某些内容设为静态最终的想法,则可以那样声明 List。 static final 变量包含的引用永远不会改变,但您可以添加和修改其内容。

将 file-reading 代码作为实例方法塞进 Student class 似乎很混乱,您应该为它找到一个更好的地方。从文件中读取所有学生不是属于单个学生的逻辑。 Java 不是 class-oriented 或 method-oriented,而是 object-oriented。将代码放入方法中,以便它们与您调用它们的实例相关。

我的observation/s:

1) 文件中的每一行"Prog349f.txt" 代表每个学生的成绩。所以 N 行表示 class.

中的 N 个学生

2) 您想将这个学生人数存储在一个私有静态最终变量中。

这是你能做的:

1) 您可以将 getStudentNumber() 定义为静态(逻辑:关联文件是一个 class 级别文件,其中包含 class 中所有学生的成绩,因为该文件是 class级别,合理的方法可以声明为static)。

public static int getStudentNumber() {
int lines = 0;
try(Scanner two = new Scanner(new File("clients")))  {
    while(two.hasNext()) {
        lines++;
        two.nextLine();
    }
} catch (FileNotFoundException e) {
        System.out.println ("File not found!");
        System.exit(0);
}
    return(lines);
}

2) 然后在主 class 或任何其他 class 中调用 getStudentNumber() 以将此数字保存为私有静态最终变量。

public class Main {

private static final int NUMBER_OF_STUDENTS = Student.getStudentNumber();

public static void main(String[] args){

    System.out.println(NUMBER_OF_STUDENTS);

    }
}

3) 但是,你的case study的执行效率可以提高很多。您实施此方法的方式可能不是最完美的。这需要仔细分析案例。