I’m trying to write a simple program in Java in educational purposes.
Basicly you can add students and those grades and after all collect some statistics like average students grade or filtering “good” students apart from “bad” students, etc.
After you run the application in terminal you are able to add student so: -add <name>, add students grade so: -addg <name> <grade>
So I want the application to store student names and list of those grades. The data struture is pretty simple (that is what I want now, at least it seems to be proper structure for this task. It represents simple associative array of arrays in PHP or dictionary of lists in Python):
+---------------------+---------------------+
| String name | ArrayList grades |
+---------------------+---------------------+
| String anotherName | ArrayList grades |
+---------------------+---------------------+
This would be coded pretty simple in PHP or Python, but in Java I’ve ran into a problem:
I just can’t construct such structure:
$ javac StudentGrades.java
StudentGrades.java:19: variable grades might not have been initialized
grades.add(5.0f);
^
Note: StudentGrades.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
1 error
StudentGrades.java:
public class StudentGrades {
Dictionary studentGrades;
/**
* @param args the command line arguments
*/
public void main(String[] args) {
//Scanner scanner = new Scanner(System.in);
ArrayList grades;
boolean res;
grades.add(5.0f);
this.studentGrades.put("Nemoden", grades);
}
Could you please point me what am I doing wrong and how it should be done properly.
Thank you.
Instead of
ArrayList grades;you’d have to useArrayList grades = new ArrayList();Yet better:
ArrayList<Float> grades = new ArrayList<Float>(); //or use Double or NumberNote that unlike C or C++ creating a variable doesn’t create the object as well.
In C++ you could imagine your code as
ArrayList* grades;i.e. you’d just create the reference/pointer here.Additional thoughts:
Dictionary studentGrades;this will be initialized to null.public void main(String[] args)that’s not a valid main function since it would have to be staticpublic static void main(String[] args)you can’t usethissince you don’t have an object instance in the static contextDictionarysince it is abstract. Use one of its subclasses, e.g.new Hashtable<String, List<Float>>(), or a map, e.g.Map<String, List<Float> dictionary = new HashMap<String, List<Float>>();boolean res;In Java only class members are initialized, local variables are not.