Flightless_bird Flightless_bird - 4 years ago 147
Java Question

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

First things first... I am new at java and have only very recently begun experimenting with multi-class and multi-method code.

So, I have a program that I have to write that takes the grades of students in a class (read from an external file) and then calculate the final grade for each student. I am currently writing the bit of code that determines how many students are in the class. This involves counting the number of lines in the external file.

This is what I have so far...

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;
// 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;

I have decided that I want to save the number of lines/number of students as a private static final int, (the current classification is just a placeholder). I am just not quite sure how to save it as such. In all of the examples, private static final(s) are declared like this:

private static final double PI = 3.14;

I am more than sure that this has been covered many times already, but what is the protocol for defining a public static final using a method?

Answer Source

You have misunderstood what static final is for, it's only for cases where a value can be set at the time that the class is loaded, and never changes after that. It's useful for declaring constants (like PI in your example) where you know what it should hold before the program ever runs.

Instead, for each line you read in, create a Student and add it to a list. Whenever you want the number of students you can call the size method on the list.

If you are really attached to the idea of making something static final, you could declare the List that way. The reference that the static final variable contains never changes but you can add to and modify its contents.

Cramming the file-reading code into the Student class as an instance method seems confused, you should find a better place for it. Reading all of the students from a file is not logic that belongs to an individual Student. Java isn't class-oriented or method-oriented, it's object-oriented. Put code in methods so they will be relevant to the instance you call them on.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download