Java using HashMap userinput loop - java

I saw a student registration sample and wanted to write it using HashMap in my own way to learn more about HashMap.
About the program:
1)You can add student name and student id -class Student
import java.util.*;
public class Student {
Scanner userInput = new Scanner(System.in);
public String sName(){
System.out.print("Enter student name: ");
String sName = userInput.next();
return sName;
}
public char sID(){
System.out.print("Enter student ID: ");
char sID= userInput.next().charAt(0);
return sID;
}
}
2)A class where I have declared 2 HashMap variables, one for student name and id and the second one for GPA and id -class AddInfo
import java.util.*;
public class AddInfo {
public HashMap<String,Character> studentInfo= new HashMap<String,Character>();
public HashMap<Double,Character> studentGPAInfo= new HashMap<Double,Character>();
}
3)You can add student GPA and student id – class StudentGPA
import java.util.*;
public class StudentGPA {
Scanner userInput = new Scanner(System.in);
public double sGPA(){
System.out.print("Enter student GPA: ");
double sGPA = userInput.nextDouble();
return sGPA;
}
public char sID(){
System.out.print("Enter student ID: ");
char sID= userInput.next().charAt(0);
return sID;
}
}
4)The last one where all the information from the above classes are getting utilized using .put - class GetInfo
import java.util.*;
public class GetInfo {
public HashMap<String,Double> myStudent=new HashMap<String,Double>();
public void addName(){
Student s= new Student();
StudentGPA sG= new StudentGPA();
AddInfo ai= new AddInfo();
ai.studentInfo.put(s.sName(), s.sID());
ai.studentGPAInfo.put(sG.sGPA(),sG.sID());
if(s.sID()== sG.sID()){
myStudent.put(s.sName(), sG.sGPA());
System.out.println("For student id "+ s.sID()+ "you have " + myStudent);
}
}
}
5)Main class
public class Main {
public static void main (String []args){
GetInfo g= new GetInfo();
g.addName();
}
}
My Problem: I think my issue is in the 4th point (GetInfo class) where I am trying to evaluate if the 2 student IDs are same or not. If they are same then put them in a different HashMap variable.
if(s.sID()== sG.sID())
When I execute the program it keeps on asking for Enter Student ID.
Any direction/advice will be helpful. Thank You for your valuable time and input.

Each time you do
if(s.sID()== sG.sID())
You are calling the sID() method of the class StudentGPA, which reads:
public char sID(){
System.out.print("Enter student ID: ");
char sID= userInput.next().charAt(0);
return sID;
}
So of course you are being prompted for input.
You should write a setSid() that sets the value in a instance variable, and then a getSid() method that only returns the sID value without prompting for input.
Then you if statement will look like this:
if(s.getSid()== sG.getSid())

You have to one time init values and then use getter to get value
public class StudentGPA {
private double sGPA;
private char sID;
Scanner userInput = new Scanner(System.in);
public void initSGPA(){
System.out.print("Enter student GPA: ");
sGPA = userInput.nextDouble();
}
public void initsID(){
System.out.print("Enter student ID: ");
sID= userInput.next().charAt(0);
}
public double getSGPA()
{
return sGPA;
}
public char getSID()
{
return sID;
}
}
In my opinion, the better way is using bean
public class StudentGPA {
private double sGPA;
private char sID;
Scanner userInput = new Scanner(System.in);
public void setSGPA(double sGPA){
this.sGPA = sGPA;
}
public void setSID(char sID){
this.sID= sID;
}
public double getSGPA()
{
return sGPA;
}
public char getSID()
{
return sID;
}
}
..... move user intput into addName or separate procedure in GetInfo class
....
System.out.print("Enter student GPA: ");
sG.setSGPA(userInput.nextDouble());
System.out.print("Enter student ID: ");
sG.setSID(userInput.next().charAt(0));
.....
AddInfo ai= new AddInfo();
ai.studentInfo.put(s.getSName(), s.getSID());
ai.studentGPAInfo.put(sG.getSGPA(),sG.getSID());

Related

Need help sorting ArrayList & Calculating averages of test scores

I tried adding a new class per a suggestion I was given, which is seen at line 67. I am unsure how to link the new class with the entries created from user input and the goal is to sort the ArrayList by the last name and to calculate averages of each of the entries 4 test scores, resulting in an average score - I would like the average score to be added to each students entry and added to the final ArrayList
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
//information given by user input that will eventually go into the ArrayList
public class studentInformation {
public static <T> void main(String[] args) {
//creating ArrayList to hold the objects created above
ArrayList<Object> studentdatabase = new ArrayList<Object>();
char cont;
do {
Scanner fnInput = new Scanner(System.in);
System.out.println("Enter Student's First Name & Press Enter");
//String fn = fnInput.nextLine();
studentdatabase.add(fnInput.nextLine());
Scanner lnInput = new Scanner(System.in);
System.out.println("Enter Student's Last Name & Press Enter");
//String ln = lnInput.nextLine();
studentdatabase.add(lnInput.nextLine());
Scanner score1Input = new Scanner(System.in);
System.out.println("Enter Student's First Exam Score & Press Enter");
//int score1 = score1Input.nextInt();
studentdatabase.add(score1Input.nextInt());
Scanner score2Input = new Scanner(System.in);
System.out.println("Enter Student's Second Exam Score & Press Enter");
//int score2 = score2Input.nextInt();
studentdatabase.add(score2Input.nextInt());
Scanner score3Input = new Scanner(System.in);
System.out.println("Enter Student's Third Exam Score & Press Enter");
//int score3 = score3Input.nextInt();
studentdatabase.add(score3Input.nextInt());
Scanner score4Input = new Scanner(System.in);
System.out.println("Enter Student's Fourth/Final Exam Score & Press Enter");
//int score4 = score4Input.nextInt();
studentdatabase.add(score4Input.nextInt());
Scanner continueInput = new Scanner(System.in);
System.out.println("Enter 'C' to end or 'A' to Add More");
cont = continueInput.next().charAt(0);
//calculate the average score for each student
//sort the ArrayList prior to printing
//Collections.sort(studentdatabase);
//Prints out the arrayList
System.out.println(studentdatabase);
}
while(cont != 'c' || cont != 'C');
}
class Students {
String firstName, lastName;
int firstScore, secondScore, thirdScore, fourthScore, averagescore;
char lettergrade;
}
}
Fisrt, create a real Student class (singular, not plural). An instance of this class is only one student. It will handle average calculation in a dedicated method.
Think about using getters and setters with the correct accessors on your attributes.
public class Student {
private String firstName, lastName;
private int firstScore, secondScore, thirdScore, fourthScore, averagescore;
private char lettergrade;
public float computeAverage(){
int sum = firstScore + secondScore + thirdScore + fourthScore;
return (float) sum / 4;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getFirstScore() {
return firstScore;
}
public void setFirstScore(int firstScore) {
this.firstScore = firstScore;
}
public int getSecondScore() {
return secondScore;
}
public void setSecondScore(int secondScore) {
this.secondScore = secondScore;
}
public int getThirdScore() {
return thirdScore;
}
public void setThirdScore(int thirdScore) {
this.thirdScore = thirdScore;
}
public int getFourthScore() {
return fourthScore;
}
public void setFourthScore(int fourthScore) {
this.fourthScore = fourthScore;
}
public int getAveragescore() {
return averagescore;
}
public void setAveragescore(int averagescore) {
this.averagescore = averagescore;
}
public char getLettergrade() {
return lettergrade;
}
public void setLettergrade(char lettergrade) {
this.lettergrade = lettergrade;
}
}
Then, don't use Object in your list but Student. You created an object. Use it !
You can't sort the list until you're done with feeding it. Put the sort out of the loop.
cont != 'c' || cont != 'C'
will always be true. So you will never get out of your loop.
Finally, I would suggest something like this.
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Scanner;
public class Main {
public static <T> void main(String[] args) {
//creating ArrayList to hold the objects created above
ArrayList<Student> studentdatabase = new ArrayList<Student>();
char cont;
do {
Student currentStudent = new Student();
Scanner fnInput = new Scanner(System.in);
System.out.println("Enter Student's First Name & Press Enter");
currentStudent.setFirstName(fnInput.nextLine());
Scanner lnInput = new Scanner(System.in);
System.out.println("Enter Student's Last Name & Press Enter");
currentStudent.setLastName(lnInput.nextLine());
Scanner score1Input = new Scanner(System.in);
System.out.println("Enter Student's First Exam Score & Press Enter");
currentStudent.setFirstScore(score1Input.nextInt());
Scanner score2Input = new Scanner(System.in);
System.out.println("Enter Student's Second Exam Score & Press Enter");
currentStudent.setSecondScore(score2Input.nextInt());
Scanner score3Input = new Scanner(System.in);
System.out.println("Enter Student's Third Exam Score & Press Enter");
currentStudent.setThirdScore(score3Input.nextInt());
Scanner score4Input = new Scanner(System.in);
System.out.println("Enter Student's Fourth/Final Exam Score & Press Enter");
currentStudent.setFourthScore(score4Input.nextInt());
studentdatabase.add(currentStudent);
Scanner continueInput = new Scanner(System.in);
System.out.println("Enter 'C' to end or 'A' to Add More");
cont = continueInput.next().charAt(0);
//Prints out the arrayList
System.out.println(studentdatabase);
}
while(cont != 'c' && cont != 'C');
//sort the arrayList prior to printing
studentdatabase.sort(Comparator.comparing(Student::getLastName));
//studentdatabase.sort(Comparator.comparing(Students::getLastName).reversed());
for (Student student:studentdatabase) {
System.out.println(student.getLastName() + " " + student.getFirstName() + " : " + student.computeAverage());
}
}
}

Multiple new returns of Scanner from a single method

to make my code cleaner I was wondering if I could separate the scanner inputs to a different method. Yet, as soon as I did it, I ran into many errors and am unable to perform the tasks.
Code for main:
public static void main(String[] args){
Task taskObject = new Task();
taskObject.taskInput();
taskObject.taskOutput(id, keyword, price);
}
Code for Task class:
import java.util.Scanner;
public class Task{
public task taskInput(){
Scanner scan = new Scanner(System.in);
System.out.println("\nEnter the id: ");
int id = scan.nextInt();
System.out.println("\nEnter the keyword: ");
String keyword = scan.nextLine();
System.out.println("\nEnter the price: ");
double price = scan.nextDouble();
return task(id, keyword, price);
}
public void taskOutput(int id, String keyword, double price){
System.out.println(id);
System.out.println(keyword);
System.out.println(price);
}
}
id, keyword and price are local variables in the scope of taskInput, and you cannot relate to them after the method has terminated. One possible approach would be to make the Task object stateful, and save them as members:
import java.util.Scanner;
public class Task{
private int id;
private String keyword;
private double price;
public void taskInput(){
Scanner scan = new Scanner(System.in);
System.out.println("\nEnter the id: ");
id = scan.nextInt();
System.out.println("\nEnter the keyword: ");
keyword = scan.nextLine();
System.out.println("\nEnter the price: ");
price = scan.nextDouble();
}
public void taskOutput() {
// Note that id, keyword and price are now members
System.out.println(id);
System.out.println(keyword);
System.out.println(price);
}
public static void main(String[] args){
Task taskObject = new Task();
taskObject.taskInput();
taskObject.taskOutput();
}
}

Why is my user input returning null in main method?

I'm new to Java and this is about to make me tear my hair out. Please note I added a print statement to ensure that Scanner was working correctly.
package dknowlton_program5;
import java.util.Scanner;
//Driver ~ Gathers Input
public class DKnowlton_MartianMaker {
static Scanner userInput = new Scanner(System.in);
public static String name;
public static int eyes, arms;
public static void main(String[] String)
{
printWelcome();
getName();
getEyes();
getArms();
System.out.print("Your martian " + name + " has... ");
}
public static void printWelcome()
{
System.out.print("Welcome to the Martian Program Revamped!");
}
public static String getName()
{
System.out.print("\nWhat would you like to name your martian? ");
String name = userInput.nextLine();
System.out.println(name);
return name;
}
public static int getEyes()
{
System.out.print("How many eyes does your martian have? ");
int eyes = userInput.nextInt();
return eyes;
}
public static int getArms()
{
System.out.print("How many arms does your martian have? ");
int arms = userInput.nextInt();
return arms;
}
}
The following should work. Notice that the static variables at the top have been removed, and instead we now save the results that are returned from the functions.
I'd suggest reading up about scope in java, in general it's best to have the lowest level of scope possible, avoid global variables were possible.
package dknowlton_program5;
import java.util.Scanner;
//Driver ~ Gathers Input
public class DKnowlton_MartianMaker {
static Scanner userInput = new Scanner(System.in);
public static void main(String[] String)
{
printWelcome();
String name = getName();
int eyes = getEyes();
int arms = getArms();
System.out.print("Your martian " + name + " has... ");
}
public static void printWelcome()
{
System.out.print("Welcome to the Martian Program Revamped!");
}
public static String getName()
{
System.out.print("\nWhat would you like to name your martian? ");
String name = userInput.nextLine();
System.out.println(name);
return name;
}
public static int getEyes()
{
System.out.print("How many eyes does your martian have? ");
int eyes = userInput.nextInt();
return eyes;
}
public static int getArms()
{
System.out.print("How many arms does your martian have? ");
int arms = userInput.nextInt();
return arms;
}
}
Instead of System.out.print("Your martian " + name + " has... ");
shouldn't you use System.out.println("Your Martian " + getName() + " has... ");
Hope it works.
EDIT: Why did you declare the String name twice?
SECOND EDIT: Try this
package dknowlton_program5;
import java.util.Scanner;
//Driver ~ Gathers Input
public class DKnowlton_MartianMaker {
Scanner userInput = new Scanner(System.in);
public String name;
public static int eyes, arms;
public static void main(String[] String)
{
DKnowlton_MartianMaker start = new DKnowlton_MartianMaker();
start.printWelcome();
start.getName();
start.getEyes();
start.getArms();
System.out.print("Your martian " + getName() + " has... ");
}
public void printWelcome()
{
System.out.print("Welcome to the Martian Program Revamped!");
}
public String getName()
{
System.out.print("\nWhat would you like to name your martian? ");
name = userInput.nextLine();
System.out.println(name);
return name;
}
public int getEyes()
{
System.out.print("How many eyes does your martian have? ");
int eyes = userInput.nextInt();
return eyes;
}
public int getArms()
{
System.out.print("How many arms does your martian have? ");
int arms = userInput.nextInt();
return arms;
}
}
this "Name" :
public static String name;
is differnt form this "Name" :
String name = userInput.nextLine();
you assign the value to the second one , and print the first one , that is why you get null.
you can simply remove the String and use the same "name " you define at beginning (the first one) :
package dknowlton_program5;
import java.util.Scanner;
//Driver ~ Gathers Input
public class DKnowlton_MartianMaker {
static Scanner userInput = new Scanner(System.in);
public static String name;
public static int eyes, arms;
public static void main(String[] String)
{
printWelcome();
getName();
getEyes();
getArms();
System.out.print("Your martian " + name + " has... ");
}
public static void printWelcome()
{
System.out.print("Welcome to the Martian Program Revamped!");
}
public static String getName()
{
System.out.print("\nWhat would you like to name your martian? ");
name = userInput.nextLine();
System.out.println(name);
return name;
}
public static int getEyes()
{
System.out.print("How many eyes does your martian have? ");
int eyes = userInput.nextInt();
return eyes;
}
public static int getArms()
{
System.out.print("How many arms does your martian have? ");
int arms = userInput.nextInt();
return arms;
}
}

Incompatible types: Object cannot be converted to another Object?

I am trying to work out what may be causing this problem for a while now. I am completely new to Java and BlueJ but have been looking at this for hours and cannot figure out what is causing the problem. Keep getting the error message "Incompatible types: Plasterer cannot be converted to Apprentice". Any help is greatly appreciated.
//Purpose of Program: To create a mixed array to hold 2 different Apprentice objects - Plasterer and Carpenter
//Plasterer and Carpenter
//All the details of each object are then displayed to the screen.
public class MixedLists
{
public static void main(String args[])
{
//Declaration of object list to hold 2 student objects
Apprentice [] apprenticeList = new Apprentice[2];
////////////////////////////////////////////////////////////////////
//Plasterer
//Taking in values
String NameIn, NumberIn, AddressIn, StudentIDIn, EmployerNameIn, FinalSem1GradeIn;
System.out.println("Entering data for Plasterer");
//Apprentice class attributes
System.out.print("\tEnter Name: ");
NameIn = EasyScanner.nextString();
System.out.print("\tEnter telephone number: ");
NumberIn = EasyScanner.nextString();
System.out.print("\tEnter Address: ");
AddressIn = EasyScanner.nextString();
System.out.print("\tEnter student id: ");
StudentIDIn = EasyScanner.nextString();
//Plasterer class attributes
System.out.print("\tEnter in Employer Name: ");
EmployerNameIn = EasyScanner.nextString();
System.out.print("\tEnter Final Semester 1 Grade: ");
FinalSem1GradeIn = EasyScanner.nextString();
//Initializing what is referenced by position 0 of the object list with a plasterer object
apprenticeList[0]=new Plasterer(NameIn, NumberIn, AddressIn, StudentIDIn, EmployerNameIn, FinalSem1GradeIn);
System.out.println("\n");
/////////////////////////////////////////////////////////////////
//Carpenter
String NameIn1,AddressIn1,Number1,StudentID1;
//additional variables
String awardSought,specialisation;
double gpaModuleGrade, industrialExperienceMark;
//Entering values for Carpenter
System.out.println("Entering data for Carpenter");
//Apprentice class attributes
System.out.print("\tEnter Name: ");
NameIn1 = EasyScanner.nextString();
System.out.print("\tEnter telephone number: ");
Number1 = EasyScanner.nextString();
System.out.print("\tEnter Address: ");
AddressIn1= EasyScanner.nextString();
System.out.print("\tEnter student id: ");
StudentID1= EasyScanner.nextString();
//Carpenter class attributes
System.out.print("\tEnter award sought: ");
awardSought = EasyScanner.nextString();
System.out.print("\tEnter specialist area: ");
specialisation = EasyScanner.nextString();
//Carpenter class attributes
System.out.print("\tEnter GPA Module Grade: ");
gpaModuleGrade = EasyScanner.nextString();
System.out.print("\tEnter industrial experience Grade: ");
industrialExperienceMark = EasyScanner.nextString();
//Initializing what is referenced by position 1 of the object list with a Carpenter object
apprenticeList[1]=new Carpenter(NameIn1, AddressIn1, Number1, StudentID1,awardSought,specialisation, gpaModuleGrade,industrialExperienceMark);
System.out.println("\n");
////////////////////////////////////////////////////////////////////
//for loop to display out contents of mixed object array
//Display out all information associated with Carpenter, Carpenter and CabinetMaker
System.out.println("Award Details for all Apprentices in the System\n");
for(int i = 0; i < apprenticeList.length; i++)
{
System.out.println(apprenticeList[i].printAwardDetails());
}
}
}
The Apprentice Class goes as such
public abstract class Apprentice
{
//attributes
private String Name;
private String Number;
private String Address;
private String StudentID;
public Apprentice (String NameIn, String NumberIn, String AddressIn, String StudentIDIn)
{
Name = NameIn;
Number = NumberIn;
Address = AddressIn;
StudentID = StudentIDIn;
}
//Methods to read the attributes
public String getName()
{
return Name;
}
public String getNumber()
{
return Number;
}
public String getAddress()
{
return Address;
}
public String getStudentID ()
{
return StudentID ;
}
public void setName(String NameIn)
{
Name = NameIn;
}
public void setNumber(String NumberIn)
{
Number = NumberIn;
}
public void setAddress(String AddressIn)
{
Address = AddressIn;
}
public void setStudentID (String StudentIDIn )
{
StudentID = StudentIDIn;
}
}
You need to use inheritance.
Create a class named for example "Worker", then Plasterer and Apprentice should both inherit that class. You then can have a list of workers containing both Plasterers and Apprentice.
Or if "Apprentice" is just a type of Plasterer, make Apprentice inherit Plasterer (or the opposite if Plasterer is a kind of Apprentice)

ArrayList and sorting method for names

I am almost done with this project. I need help figuring out why it does not pause after asking for the last name before it asks for the first name. I also keep getting an error when I try to add a new Comparator to sort by score.
package student.scores;
import java.util.Scanner;
import java.util.Arrays;
import java.util.Comparator;
import java.util.ArrayList;
import java.util.*;
public class StudentScores{
public static void main(String[] args) {
System.out.println("Welcome to the Student Scores Application.");
Scanner input = new Scanner (System.in);
System.out.println("Enter number of students: ");
int numStudents = input.nextInt();
List<Student> students = new ArrayList<>();
for (int i = 0; i < numStudents; i++) {
System.out.println("Enter Student Last Name: ");
String lastName = input.nextLine();
System.out.println("Enter Student First Name: ");
String firstName = input.nextLine();
System.out.println("Enter Student Score: ");
int score = input.nextInt();
students.add(new Student(lastName, firstName, score));
}
Collections.sort(students);
System.out.println("Students in alphabetical order");
for (Student s : students) {
System.out.println(s);
}
Collections.sort(students, new Comparator() {});
System.out.println("Students by score");
for (Student s : students) {
System.out.println(s);
}
static class Student implements Comparable<Student>
{
private String lastName;
private String firstName;
private int scores;
public Student (String lastName, String firstName, int score)
{
this.lastName = lastName;
this.firstName = firstName;
this.scores = score;
}
public int getScores()
{
return scores;
}
public String getLastName()
{
return lastName;
}
public String getFirstName()
{
return firstName;
}
#Override
public int compareTo(Student s)
{
if (s.lastName.equals(lastName))
{
return firstName.compareToIgnoreCase(s.firstName);
}
return lastName.compareToIgnoreCase(s.lastName);
}
static class StudentScoreComparator implements Comparator<Student>
{
#Override
public int compare(Student o1, Student o2)
{
return (Integer.valueOf(o1.getScores())).compareTo(o2.getScores());
}
}
#Override
public String toString() {
return String.format("%s %s %d", firstName, lastName, scores);
}
}
}
I believe the easiest approach for also sorting by score is to add a second class that implements Comparator<Student> like
static class StudentScoreComparator implements Comparator<Student> {
#Override
public int compare(Student o1, Student o2) {
return (Integer.valueOf(o1.getScores())).compareTo(o2.getScores());
}
}
Then you can pass an instance of that Comparator to the sort methods, and sort by score.
Edit
Then I would add a toString() to Student like
#Override
public String toString() {
return String.format("%s %s %d", firstName, lastName, scores);
}
Edit 2
I think your main() was supposed to look like,
public static void main(String[] args) {
System.out.println("Welcome to the Student Scores Application.");
Scanner input = new Scanner (System.in);
System.out.println("Enter number of students: ");
int numStudents = input.nextInt();
List<Student> students = new ArrayList<>();
for (int i = 0; i < numStudents; i++) {
System.out.println("Enter Student Last Name: ");
String lastName = input.nextLine();
System.out.println("Enter Student First Name: ");
String firstName = input.nextLine();
System.out.println("Enter Student Score: ");
int score = input.nextInt();
students.add(new Student(lastName, firstName, score));
}
Collections.sort(students);
System.out.println("Students in alphabetical order");
for (Student s : students) {
System.out.println(s);
}
Collections.sort(students, new StudentScoreComparator());
System.out.println("Students by score");
for (Student s : students) {
System.out.println(s);
}
}
Your code is not using the Student class at all. You need to be capturing the first name, last name, and score of each Student and storing the entry in an array of Student objects.
System.out.print("Enter student's first name: ");
String fname = input.next(); // Since names should not have white spaces, use next() instead of nextLine()
System.out.print("Enter student's last name: ");
String lname = input.next();
System.out.print("Enter student's score");
int score = input.next();
record[i] = new Student(fname, lname, score);
The code snippet above should be inside your loop. Each iteration you are capturing a student's full name and score, and adding a new instance of Student inside your Student array. The way I understood your assignment, each Student object represents a record. The array can (and will) have multiple entries for a particular student, but not necessarily in order. The sorting helps with printing out all records for the same student one after the other. For example, index 0 of the array could be for "Joe Smith" while index 1 could be for "Anne Johnson". When sorted, all of the records for Anne Johnson should be listed first, then Joe Smith's records.
To sort by name, you need to compare the current index to the next, if there is one to compare. First, you must grab the last name and compare them. If they are equal, grab the first name. If they are equal, assume they (the records) are for the same student (and you can decide at that point to grab the score to sort by score). If the names are different, the records are for different students so you must execute sorting. I am sure this is a school assignment, so use one of the sorting algorithms taught in class (maybe bubble sort) and sort the array. Most likely, you will need multiple passes for the array to be fully sorted by name and scores.
I figured out my problem. I added an import for the Comparable method. I also changed it to add a line between the output.
package student.scores;
import java.util.Scanner;
import java.util.Comparator;
import java.util.ArrayList;
import java.util.*;
import student.scores.StudentScores.Student.StudentScoreComparator;
public class StudentScores{
public static void main(String[] args) {
System.out.println("Welcome to the Student Scores Application.");
Scanner input = new Scanner (System.in);
System.out.println("Enter number of students: ");
int numStudents = input.nextInt();
List<Student> students = new ArrayList<>();
int counter = 1;
for(int i = 0; i < numStudents; i++) {
int studentNum = counter++;
System.out.println("\nStudent " + studentNum);
System.out.println("Enter Student Last Name: ");
String lastName = input.next();
System.out.println("Enter Student First Name: ");
String firstName = input.next();
System.out.println("Enter Student Score: ");
int score = input.nextInt();
students.add(new Student(lastName, firstName, score));
}
Collections.sort(students);
System.out.println("Students in alphabetical order: ");
for (Student s : students) {
System.out.println(s);
}
System.out.println();
Collections.sort(students, new StudentScoreComparator());
System.out.println("Students by score:");
for (Student s : students) {
System.out.println(s);
}
}
static class Student implements Comparable<Student>
{
private String lastName;
private String firstName;
private int scores;
public Student (String lastName, String firstName, int score)
{
this.lastName = lastName;
this.firstName = firstName;
this.scores = score;
}
public int getScores()
{
return scores;
}
public String getLastName()
{
return lastName;
}
public String getFirstName()
{
return firstName;
}
#Override
public int compareTo(Student s)
{
if (s.lastName.equals(lastName))
{
return firstName.compareToIgnoreCase(s.firstName);
}
return lastName.compareToIgnoreCase(s.lastName);
}
static class StudentScoreComparator implements Comparator<Student>
{
#Override
public int compare(Student o1, Student o2)
{
return (Integer.valueOf(o1.getScores())).compareTo(o2.getScores());
}
}
#Override
public String toString() {
return String.format("%s %s %d", firstName, lastName, scores);
}
}
}

Categories