3.6. HashMap
Mon Sep 19 2022 03:54:11 GMT+0000 (Coordinated Universal Time)
Saved by
@cruz
#javascript
package org.launchcode.java.demos.collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class HashMapGradebook {
public static void main(String[] args) {
HashMap<String, Double> students = new HashMap<>();
Scanner input = new Scanner(System.in);
String newStudent;
System.out.println("Enter your students (or ENTER to finish):");
// Get student names and grades
do {
System.out.print("Student: ");
newStudent = input.nextLine();
if (!newStudent.equals("")) {
System.out.print("Grade: ");
Double newGrade = input.nextDouble();
students.put(newStudent, newGrade);
// Read in the newline before looping back
input.nextLine();
}
} while(!newStudent.equals(""));
// Print class roster
System.out.println("\nClass roster:");
double sum = 0.0;
for (Map.Entry<String, Double> student : students.entrySet()) {
System.out.println(student.getKey() + " (" + student.getValue() + ")");
sum += student.getValue();
}
double avg = sum / students.size();
System.out.println("Average grade: " + avg);
}
}
//Notice how a HashMap called students is declared on line 11:
HashMap<String, Double> students = new HashMap<>();
//Here, <String, Double> defines the data types for this map’s <key, value> pairs. Like the ArrayList, when we call the HashMap constructor on the right side of the assignment, we don’t need to specify type.
//We can add a new item with a .put() method, specifying both key and value:
students.put(newStudent, newGrade);
content_copyCOPY
https://education.launchcode.org/java-web-development/chapters/control-flow-and-collections/hashmap.html
Comments