Skip to content

Commit 4015c82

Browse files
committed
add hashmap gradebook example
1 parent 3cc3c4c commit 4015c82

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package org.launchcode.java.demos.collections;
2+
3+
import java.util.HashMap;
4+
import java.util.Map;
5+
import java.util.Scanner;
6+
7+
public class HashMapGradebook {
8+
public static void main(String[] args) {
9+
10+
HashMap<String, Double> students = new HashMap<>();
11+
Scanner in = new Scanner(System.in);
12+
String newStudent;
13+
14+
System.out.println("Enter your students (or ENTER to finish):");
15+
16+
// Get student names and grades
17+
do {
18+
19+
System.out.print("Student: ");
20+
newStudent = in.nextLine();
21+
22+
if (!newStudent.equals("")) {
23+
System.out.print("Grade: ");
24+
Double newGrade = in.nextDouble();
25+
students.put(newStudent, newGrade);
26+
27+
// Read in the newline before looping back
28+
in.nextLine();
29+
}
30+
31+
} while(!newStudent.equals(""));
32+
33+
// Print class roster
34+
System.out.println("\nClass roster:");
35+
double sum = 0.0;
36+
37+
for (Map.Entry<String, Double> student : students.entrySet()) {
38+
System.out.println(student.getKey() + " (" + student.getValue() + ")");
39+
sum += student.getValue();
40+
}
41+
42+
double avg = sum / students.size();
43+
System.out.println("Average grade: " + avg);
44+
}
45+
}

0 commit comments

Comments
 (0)