I started a simple project, but I've encountered a problem.
Main class
public static void main(String[] args){
/*
• Ask the user how many new students will be added to the database.
• The user should be prompted to enter a name and year for each student.
• The student should have a unique 5-digit id, with the first being their grade level.
• The student should have several course options to choose from.
• Each course costs $600 to enroll.
• The student should be able to check their balance and pay tuition.
• The status of the student should show their name, id, courses, and balance.
*/
Scanner input = new Scanner(System.in);
Scanner n = new Scanner(System.in);
int numberOfStudents=0,year;
String firstName,lastName;
System.out.println("How many students will attend this School? ");
//input number of students
System.out.print("Input : ");
numberOfStudents = input.nextInt();
//end
//Input name and year for every student
Student students [] = new Student[numberOfStudents];
Deposit deposit [] = new Deposit[numberOfStudents];
for(int i = 0 ; i < numberOfStudents ;i ++){
students[i]=new Student();
deposit[i]=new Deposit(students[i]);
//It consumes the /n character
input.nextLine();
//
System.out.print("Insert First name : ");
firstName=input.nextLine();
students[i].setFirstName(firstName);
System.out.print("Insert last name : ");
lastName=input.nextLine();
students[i].setLastName(lastName);
System.out.print("Input year :");
year=input.nextInt();
students[i].setYear(year);
//set cash test
students[i].setCash(1000);
//end
}
for(int j = 0 ; j < numberOfStudents ; j++){
System.out.println("Student " + j + " First name " + students[j].getFirstName() + " has " + deposit[j].getBalance());
}
//end
}
Student class
private String firstName,lastName;
private int year,grade,cash;
private int[] studentID = new int[5];
public Student(){
}
public Student(String firstName, String lastName, int year) {
this.firstName = firstName;
this.lastName = lastName;
this.year = year;
}
public Student(String firstName, String lastName, int year, int grade, int cash) {
this.firstName = firstName;
this.lastName = lastName;
this.year = year;
this.grade = grade;
this.cash=cash;
}
private int[] RandomID(){
Random rand = new Random();
this.studentID[0] = this.grade;
for(int i = 1; i <= this.studentID.length-1 ; i ++ ){
int randomNumbers = rand.nextInt(10);
this.studentID[i] = randomNumbers;
}
return this.studentID;
}
public int[] getStudentID() {
return RandomID();
}
public int getCash() {
return cash;
}
public void setCash(int cash) {
this.cash=cash;
}
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 getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
Deposit class:
private Student student;
private int balance;
public Deposit(){
}
public Deposit(Student student){
this.student = student;
this.balance=student.getCash();
}
public void checkBalance(){
System.out.println("You have " + this.student.getCash() + " on this account");
}
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
public int getBalance() {
return this.balance;
}
public void setBalance(int balance) {
this.balance = balance;
}
When I call in Main System.out.println(deposit[j].getBalance());, it says it's 0, but I put it in the constructor in the Deposit class.
Shouldn't this.balance have a value from student.getCash()?
The checkBalance method in deposit gives me the value that I need when I call it in the main class student.getCash().
You're initializing the Deposit with a Student instance before you initialize its cash, so it'll be 0. Move the initialization of the Deposit after you're done initializing the corresponding Student and you should be OK:
for(int i = 0 ; i < numberOfStudents ;i ++){
students[i]=new Student();
//It consumes the /n character
input.nextLine();
//
System.out.print("Insert First name : ");
firstName=input.nextLine();
students[i].setFirstName(firstName);
System.out.print("Insert last name : ");
lastName=input.nextLine();
students[i].setLastName(lastName);
System.out.print("Input year :");
year=input.nextInt();
students[i].setYear(year);
//set cash test
students[i].setCash(1000);
//end
deposit[i]=new Deposit(students[i]);
}
The value is being set at the time you create a Deposit object, which is immediately after you create a new Student object. At that time, the value of cash in the Student instance is zero. You don't set that until later. You could do something like:
public int getBalance() {
return this.student.getCash();
}
Instead of setting a balance member once, this would call the method on the Student instance each time to get the updated value. I'm not saying this is the best design, but it appears to be what you expected to happen.
Related
I created a three-class program. In the third class, I should fill the array with the values "name", "surname", "code", and "age". What happens though is that my array is always "null", and I can't fill it. Thank you all for your help.
First class:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String name, surname;
int code, age, i=0, min=150;
System.out.println("How many teachers do you want to enter information?");
i=in.nextInt();
for(int j=0; j<i; j++)
{
System.out.println("Enter the teacher's name");
name=in.next();
System.out.println("Enter the teacher's surname");
surname=in.next();
System.out.println("Enter the teacher's code");
code=in.nextInt();
System.out.println("Enter the teacher's age");
age=in.nextInt();
Teacher d = new Teacher(name, surname, code, age);
System.out.println(d.getCode());
System.out.println(d.getSurname());
System.out.println(d.getAge());
University c = new University(name, surname, code, age);
min=c.MinimumAge(age, min);
}
System.out.println(min);
}
}
Second class:
public class Teacher
{
protected String name;
protected String surname;
protected int code;
protected int age;
public Teacher(String name, String surname, int code, int age)
{
this.name=name;
this.surname=surname;
this.code=code;
this.age=age;
}
public String getName()
{
return name;
}
public int getCode()
{
return code;
}
public String getSurname()
{
return surname;
}
public int getAge()
{
return age;
}
}
Third class (I put "0" as a location for filling the array just to do tests.):
public class University
{
private Teacher[] array=new Teacher[4];;
public University(String name, String surname, int code, int age)
{
array[0] = new Teacher(name, surname, code, age);
}
public int MinimumAge(int age, int min)
{
if (age<min)
min=age;
return min;
}
}
The class University has not been implemented correctly. You can implement it as:
class University {
private int counter = 0;
private final int MAX = 4;
private Teacher[] array = new Teacher[MAX];
public void addTeacher(Teacher teacher) {
if (counter < MAX) {
array[counter++] = teacher;
}
}
public int minimumAge() {
if (counter == 0) {
return 0;
}
int min = array[0].getAge();
for (int i = 1; i < counter; i++) {
if (array[i].getAge() < min) {
min = array[i].getAge();
}
}
return min;
}
}
Accordingly, you need to change your code in main as shown below:
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String name, surname;
int code, age, i = 0, min = 150;
University university = new University();
System.out.print("How many teachers do you want to enter information?: ");
i = in.nextInt();
for (int j = 0; j < i; j++) {
System.out.print("Enter the teacher's name: ");
name = in.next();
System.out.print("Enter the teacher's surname: ");
surname = in.next();
System.out.print("Enter the teacher's code: ");
code = in.nextInt();
System.out.print("Enter the teacher's age: ");
age = in.nextInt();
university.addTeacher(new Teacher(name, surname, code, age));
}
System.out.println(university.minimumAge());
}
}
A sample run:
How many teachers do you want to enter information?: 2
Enter the teacher's name: a
Enter the teacher's surname: b
Enter the teacher's code: 1
Enter the teacher's age: 23
Enter the teacher's name: x
Enter the teacher's surname: y
Enter the teacher's code: 2
Enter the teacher's age: 15
15
I need to fix my addQuiz() in my student class. Then, with that class, I pull all the info into my main of prog2. I have everything working except two things. I need to get the formula fixed for my addQuiz() so it totals the amount of points entered, and fix the while statement in my main so that I can enter a word to tell the program that I am done entering my quizzes.
Here is my main file.
import java.util.Scanner;
public class Prog2 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Student student = new Student();
//creates array for quizzes
double[] grades = new double[99];
//counter for total number of quizzes
int num = 0;
//requests user to enter students name
System.out.print("Enter name of student: ");
String name = in .nextLine();
//requests user to enter students quizzes
System.out.print("Enter students quiz grades: ");
int quiz = in .nextInt();
while (quiz >= 1) {
System.out.print("Enter students quiz grades: ");
quiz = in .nextInt();
grades[num] = quiz;
num++;
}
//prints the name, total, and average of students grades
System.out.println();
System.out.println(name);
System.out.printf("\nTotal: ", student.addQuiz(grades, num));
System.out.printf("\nAverage: %1.2f", student.Average(grades, num));
}
}
here is my student file:
public class Student {
private String name;
private int total;
private int quiz;
static int num;
public Student() {
super();
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public int getQuiz() {
return quiz;
}
public void setQuiz(int quiz) {
this.quiz = quiz;
}
public static double addQuiz( double[] grades, int num){
int totalQuiz = 0;
for( int x = 0; x < num; x++){
totalQuiz += grades[x];
}
return totalQuiz;
}
public static double Average( double[] grades, int num){
double sum = 0;
for( int x = 0; x < num; x++){
sum += grades [x];
}
return (double) sum / num;
}
}
Any help would be much appreciated!
Your requirement is not clear but as I guess it should be something like this.
Prog2 class:
public static void main(String[] args) {
// requests user to enter students name
System.out.print("Enter name of student: ");
Scanner in = new Scanner(System.in);
String name = in.nextLine();
Student student = new Student(name);
System.out.print("Enter number of quiz: ");
int count = in.nextInt();
for (int i = 0; i < count; i++) {
// requests user to enter students quizzes
System.out.print("Enter students quiz grades: ");
int quiz = in.nextInt();
student.addGrade(quiz);
}
// prints the name, total, and average of students grades
System.out.println(name);
System.out.println("Total: " + student.getTotal());
System.out.println("Average: " + student.getAverage());
}
Student class:
private String name;
private List<Double> grades = new ArrayList<Double>();
public Student(String name) {
super();
this.name= name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void addGrade(double grade) {
this.grades.add(grade);
}
public double getTotal() {
double total = 0;
for (double grade : grades) {
total += grade;
}
return total;
}
public double getAverage() {
return (double) getTotal() / grades.size();
}
Accept the answer if it helps.
Well for the stop condition you could try something like this
String stopFrase="stop";
String userInput="";
int quiz;
//Other code
for(;;) //This basically means loop until I stop you
{
System.out.print("Enter students quiz grades type 'stop' to finish:");
userInput=in.nextLine();
if(userInput.equals(stopFrace))
{
break;//Stop the loop
}
quiz= Integer.parseInt(userInput);
//The rest of your code
}
Your addQuiz() method seems fine, if you are not getting the desired result please check your parameters, specifically make sure that number matches the number of quiz entered.
So i have 3 classes, and one that runs all the code. A student class, a Graduate student class and an undergraduate class, and a class called lab 4 that runs the code. The code asks for how many grad students and how many undergrad students there are, then asks the user to input all the information for that number of each. After all the info is inputed, the under grad or grad student objects are added to an array list of students. after all the students are added, then prints all the information. However when i input all the information, the array does not print, the program terminates. How do i get the array to print out?
Code:
Lab 4: creates the student objects, array list, adds them to the array, and the prints all information for objects added to the array list
import java.util.ArrayList;
import java.util.Scanner;
public class Lab04 {
public static void main(String[] args) {
ArrayList <Student> studentList = new ArrayList <Student>();
Scanner s = new Scanner(System.in);
System.out.println("How many Graduate Students do you want to store?");
int numOfStudents = s.nextInt();
s.nextLine();
for (int i = 0; i < numOfStudents; i++) {
System.out.println("What is the student's name?");
String name = s.nextLine();
System.out.println("What is the student's GPA?");
double GPA = s.nextDouble();
s.nextLine();
System.out.println("What is the student's ID?");
String ID = s.nextLine();
System.out.println("What is the student's High School?");
String highSchool = s.nextLine();
System.out.println("What is the student's graduate major?");
String gradMajor = s.nextLine();
System.out.println("What is the student's undergraduate major?");
String underMajor = s.nextLine();
System.out.println("What is the student's undergradute school? ");
String underSchool = s.nextLine();
GraduateStudent gradStu = new GraduateStudent(name, GPA, ID, highSchool, gradMajor, underMajor,
underSchool);
studentList.add(gradStu);
}
System.out.println("How many UnderGraduate students are there?");
int numOfUnder = s.nextInt();
s.nextLine();
for (int j = 0; j < numOfUnder; j++) {
System.out.println("What is the student's name?");
String name = s.nextLine();
System.out.println("What is the student's GPA?");
double GPA = s.nextDouble();
s.nextLine();
System.out.println("What is the student's ID?");
String ID = s.nextLine();
System.out.println("What is the student's High School?");
String highSchool = s.nextLine();
System.out.println("What is the student's major?");
String major = s.nextLine();
System.out.println("What the student's minor?");
String minor = s.nextLine();
UnderGraduate UnderGrad = new UnderGraduate(name, GPA, ID, highSchool, major, minor);
studentList.add(UnderGrad);
}
for (int j = 0; j < studentList.size(); j++) {
(studentList.get(j)).getStudentInformation();
}
}
}
Student Class:
public class Student {
private String name;
private double gpa;
private String id;
private String highSchool;
//private String major;
//private String minor;
public Student() {
name = "";
gpa = 0.0;
id = "";
highSchool = "";
//major = "";
//minor = "";
}
public Student(String name, double gpa, String id, String highSchool){
this.name = name;
this.gpa = gpa;
this.id = id;
this.highSchool = highSchool;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getGpa() {
return gpa;
}
public void setGpa(double gpa) {
this.gpa = gpa;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getHighSchool() {
return highSchool;
}
public void setHighSchool(String highSchool) {
this.highSchool = highSchool;
}
public String getStudentInformation() {
String result = "Name: " + name + " GPA: " + gpa + " ID: " + id
+ " High School: " + highSchool;
return result;
}
}
graduate Class:
public class GraduateStudent extends Student {
private String gradMajor;
private String underMajor;
private String underSchool;
public GraduateStudent(String name, double gpa, String id, String highSchool,
String gradMajor, String underMajor, String underSchool) {
super(name, gpa, id, highSchool);
this.gradMajor = gradMajor;
this.underMajor = underMajor;
this.underSchool = underSchool;
}
public String getGradMajor() {
return gradMajor;
}
public void setGradMajor(String gradMajor) {
this.gradMajor = gradMajor;
}
public String getUnderMajor() {
return underMajor;
}
public void setUnderMajor(String underMajor) {
this.underMajor = underMajor;
}
public String getUnderSchool() {
return underSchool;
}
public void setUnderSchool(String underSchool) {
this.underSchool = underSchool;
}
#Override
public String getStudentInformation() {
String result = super.getStudentInformation()+
"Graduate Major: " + gradMajor + "Undergraduate Major: " + underMajor +
"Undergraduate School: " + underSchool;
return result;
}
}
Because you're not printing anything. Change
for (int j = 0; j < studentList.size(); j++) {
(studentList.get(j)).getStudentInformation();
}
to
for (int j = 0; j < studentList.size(); j++) {
System.out.println((studentList.get(j)).getStudentInformation());
}
When you ask getStudentInformation, it returns a String, what you want to do now is to System.out.println(...) this String object
Could anybody tell me how to list some data in an arrayList according to the integer value that each component of the ArrayList has? This is my main class
import java.util.Scanner;
import java.io.*;
import java.util.Collections;
import java.util.ArrayList;
public class StudentDriver {
public static void main(String[] args) throws IOException {
Scanner scan, urlScan, fileScan;
String url, file;
int count = 0;
scan = new Scanner(System.in);
System.out.println("Enter the name of the file");
fileScan = new Scanner(new File("Data.csv"));
ArrayList<Student> studentList = new ArrayList<Student>();
while(fileScan.hasNext()){
url = fileScan.nextLine();
urlScan = new Scanner(url);
urlScan.useDelimiter(",");
count++;
while(urlScan.hasNext()){
String name = urlScan.next();
String last = urlScan.next();
int score = urlScan.nextInt();
Student e = new Student(name,last, score);
studentList.add(e);
}
}
System.out.println("The file has data for" +count+ "instances");
int option;
do{
System.out.println("********");
System.out.println("Options:");
System.out.println("********\n1. List \n2. Add Student \n3.Delete Student \n4. Exit \n******** ");
System.out.print("Select option: ");
option = scan.nextInt();
if(option == 1){
int index = 0;
while(index<studentList.size()){
System.out.println(studentList.get(index));
index++;
}
}
else if(option == 2){
System.out.print("Enter the name of the student: ");
String newName = scan.next();
System.out.print("Enter the last name of the student: ");
String newLastName = scan.next();
System.out.print("Enter the exam score of the student: ");
int newScore = scan.nextInt();
Student b = new Student(newName, newLastName, newScore);
studentList.add(b);}
else if(option == 3){
System.out.print("Enter the name of the student to remove: ");
String remove = scan.next();
System.out.print("Enter the last name of the student: ");
String remove1 = scan.next();
int location = studentList.indexOf(remove);
location = studentList.indexOf(remove1);
studentList.remove(location);
}
}while(option!=4 && option <4);
}//main
}//class
And this is the other class
public class Student implements Comparable<Student>{
String firstName, lastName;
int score;
public Student(String firstName, String lastName, int score){
this.firstName = firstName;
this.lastName = lastName;
this.score = score;
}
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 getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public String toString(){
return firstName + " " + lastName + ", exam score is "+ score;
}
#Override
public int compareTo(Student c) {
return score-c.getScore();
}
}
As you can see, up to now I have created the class where my compare method is but I have difficulties on using it. Also I have had difficulties on deleting one of the Array List parts by just writing the name and last name of the student. If somebody would help me, I would be very thankful.
well you can change your compareTo method as
public int compareTo(Student another)
{
if (this.score > another.score)
return -1;
if (this.score < another.score)
return 1;
else
return 0;
}
this should show it as decreasing order you can change the operator
than use whereever you want to sort it
Collections.sort(studentList)
Also if you don't want to use Collections.sort() method I can show you how you can write it with for loop under add option
Student newStd = new Student(name, last, score);
for(int i=0;studentList.size()>i;i++)
{
int size = studentList.size();
if(newStd.compareToCustom(studentList.get(i))>0)
{
studentList.add(i, newStd);
break;
}
else if(newStd.compareToCustom(studentList.get(size-1))<0)
{
studentList.add(studentList.size(), newStd);
break;
}
else if(newStd.compareToCustom(studentList.get(i))==0)
{
studentList.add(i++, newStd);
break;
}
}
for the remove part you can use
else if ( option == 3)
{
System.out.print("Enter the first name of student will be deleted: ");
String removeName = scan.next();
System.out.print("Enter the last name of student will be deleted: ");
String removeLastName = scan.next();
for ( int i = 0; i < studentList.size(); i++)
{
Student deleted = studentList.get(i);
if ( deleted.getFirstName().toLowerCase().equals(removeName.toLowerCase()) && deleted.getLastName().toLowerCase().equals(removeLastName.toLowerCase()))
{
studentList.remove(i);
System.out.println("The student has been deleted.");
break;
}
else
{
System.out.println("This student is not found");
break;
}
}
}
Basically what you want is an ordered collection. As #duffymo has stated, think about a creating a custom Comparator using your score.
There is plenty of info here
In terms of deleting students from the list.
The studentList is a list containing Student objects.
This means that the follow code:
System.out.print("Enter the name of the student to remove: ");
String remove = scan.next();
System.out.print("Enter the last name of the student: ");
String remove1 = scan.next();
int location = studentList.indexOf(remove);
Tries to find the index of a Student given the first name. This will return -1 as you're searching for a String and not a Student object.
Instead you have to iterate through your studentList and compare the first and last name of each Student element with the values of remove and remove1.
for(Student student : studentList) {
if(student.getFirstName.equals(remove) && student.getLastName.equals(remove1)) {
// remove the student.
}
}
Also you could consider giving each Student an ID as an unique identifier.
try this to sort studentList
Collections.sort(studentList, new Comparator<Student>()
{
#Override
public int compare(Student x, Student y)
{
if(x.score >= y.score)
return 1;
else
return -1;
}
});
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);
}
}
}