ArrayList and sorting method for names - java

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);
}
}
}

Related

Reading a Textfile that has names and grades to an array list to later use for average

I have a textfile that looks something like this:
**John Smith 94 88 77 99
Peter Griffin 88 34 55 78**
What I am trying to do is read each word using next() and then store that into an array list. From here. I need to identity the individual names and their respective marks. I don't know if I should be using next line so that each person is on a seperate line but what confuses me is using a for loop so that I do not need to manually hard code this. If I have 20 students each with 4 marks and a name and a last name should i store them all in arrays? I can't seem to figure out the loop restrictions. Also im trying to understand the basics behind this so nothing too complex.
public static ArrayList<String> readFile(String file)throws IOException{
ArrayList<String> list = new ArrayList<String>();
Scanner reader = new Scanner(new File("grades.txt"));
ArrayList<Integer> allMarks = new ArrayList<Integer>();
while(reader.hasNext()){
String line = reader.next();//first and last names
list.add(line);
}
//System.out.println(list);
//first students name and grades
//hard coding element here represents one student's info
String fName = list.get(8);
String lName = list.get(9);
String mark1 = list.get(10);
String mark2 = list.get(11);
String mark3 = list.get(12);
String mark4 = list.get(13);
int sum = Integer.parseInt(mark1)+Integer.parseInt(mark2)+Integer.parseInt(mark3)+Integer.parseInt(mark4);
double average = sum/4;
System.out.println(fName+lName +" "+ average);
return(list);
}
}
What I am trying to do is read each word using next() and then store that into an array list
First, create a Student object of some kind, which can hold the basic information you're loading, for example...
public class Student {
private String firstName;
private String lastName;
private List<Integer> grades;
public Student(String firstName, String lastName, List<Integer> grades) {
this.firstName = firstName;
this.lastName = lastName;
this.grades = grades;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public List<Integer> getGrades() {
return grades;
}
}
Then, use Scanner#hasNextLine and Scanner#nextLine to read the entire line of text from the file. You could use String#split, but then you'd have to manually convert the String grades to int. In this case, you can use another Scanner to simply parse the line of text, for example...
Scanner reader = new Scanner(new File("grades.txt"));
while (reader.hasNextLine()) {
String line = reader.nextLine();
Scanner parser = new Scanner(line);
String firstName = parser.next();
String lastName = parser.next();
List<Integer> grades = new ArrayList<>(4);
while (parser.hasNextInt()) {
grades.add(parser.nextInt());
}
Student student = new Student(firstName, lastName, grades);
}
This should be wrapped up into a method which stores each student in a list of some kind, for example...
public List<Student> loadStudents() throws FileNotFoundException {
List<Student> students = new ArrayList<>(16);
Scanner reader = new Scanner(new File("grades.txt"));
while (reader.hasNextLine()) {
String line = reader.nextLine();
Scanner parser = new Scanner(line);
String firstName = parser.next();
String lastName = parser.next();
List<Integer> grades = new ArrayList<>(4);
while (parser.hasNextInt()) {
grades.add(parser.nextInt());
}
Student student = new Student(firstName, lastName, grades);
students.add(student);
}
return students;
}
I need to identity the individual names and their respective marks
Okay, this is seperate work flow, so you would load the student details, then use a seperate loop to loop over the List and generate the output.
Since this is some repeating functionality, we could simply add some helper methods to the Student class to do it for us!
public class Student {
//...
public String getName() {
return (getFirstName() + " " + getLastName()).trim();
}
public int sumGrades() {
int total = 0;
for (int grade : getGrades()) {
total += grade;
}
return total;
}
public double gradeAverage() {
return sumGrades() / (double) getGrades().size();
}
}
Now, we just just loop over the List of students and print the averages, for example...
for (Student student : loadStudents()) {
System.out.println(student.getName() + " grade average " + student.gradeAverage());
}
Now, this is not the only way you could do this, but when ever you're dealing with structured data, it's a good idea to try and encapsulate it into some kind of class, it's easier then dealing with array indices 😉
Runnable example...
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
new Main();
}
public Main() throws FileNotFoundException {
for (Student student : loadStudents()) {
System.out.println(student.getName() + " grade average " + student.gradeAverage());
}
}
public List<Student> loadStudents() throws FileNotFoundException {
List<Student> students = new ArrayList<>(16);
Scanner reader = new Scanner(new File("grades.txt"));
while (reader.hasNextLine()) {
String line = reader.nextLine();
Scanner parser = new Scanner(line);
String firstName = parser.next();
String lastName = parser.next();
List<Integer> grades = new ArrayList<>(4);
while (parser.hasNextInt()) {
grades.add(parser.nextInt());
}
Student student = new Student(firstName, lastName, grades);
students.add(student);
}
return students;
}
public class Student {
private String firstName;
private String lastName;
private List<Integer> grades;
public Student(String firstName, String lastName, List<Integer> grades) {
this.firstName = firstName;
this.lastName = lastName;
this.grades = grades;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public List<Integer> getGrades() {
return grades;
}
public String getName() {
return (getFirstName() + " " + getLastName()).trim();
}
public int sumGrades() {
int total = 0;
for (int grade : getGrades()) {
total += grade;
}
return total;
}
public double gradeAverage() {
return sumGrades() / (double) getGrades().size();
}
}
}

how to add bunch of data into linked list

Basically, I just tried to learn linked lists but I can't seem to understand how to insert a bunch of data from different variables into it. Does it work as an array/ ArrayList? Before we end the loop we are supposed to store the data right, but how??
Let say I have variables ( name, age, phonenum).
'''
char stop='Y';
while(stop!='N'){
System.out.println("\nEnter your name : ");
int name= input.nextLine();
System.out.println("\nEnter your age: ");
int age= input.nextInt();
System.out.println("\nEnter your phone number: ");
int phonenum= input.nextLine();
System.out.println("Enter 'Y' to continue, 'N' to Stop: ");
stop = sc.nextLine().charAt(0);
}
'''
First, change your code to use appropriate types. Name and phone should be of type String, not int.
Define a class to hold your fields. Records are an easy way to do that.
record Person ( String name , int age , String phone ) {}
Declare your list to hold objects of that class.
List< Person > list = new LinkedList<>() ;
Instantiate some Person objects, and add to list.
list.add( New Person( "Alice" , 29 , "477.555.1234" ) ) ;
In the line above, I hard-coded some example data. In your own code, you will be passing to the constructor the variables you populated by interacting with the user.
list.add( New Person( name , age , phonenum ) ) ;
You can create an object which has name, age and phenomenon then create an insert method which you call in your while loop.
In psuedo code it would look something like this:
public class Data {
String name;
int age;
int phenomenon;
//constructor
//getters & setters
}
This class above will hold contain the user input. You can gather all the user input and store it in an array and perform the insert with array of data instead of inserting one object at a time
public void InsertData(LinkedList<Data> list, Arraylist<Data> input) {
for(Data d: input){
list.add(d);
}
}
You can read up on linkedlists a bit more here to understand how exactly linkedlists work and implement your own from scratch: https://www.geeksforgeeks.org/implementing-a-linked-list-in-java-using-class/
Try this
Possibility : 1
import java.util.*;
public class Naddy {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
char stop = 'Y';
LinkedList<Object> list = new LinkedList<Object>();
while (stop != 'N') {
System.out.println("\nEnter your name : ");
String name = input.nextLine();
System.out.println("\nEnter your age: ");
int age = input.nextInt();
System.out.println("\nEnter your phone number: ");
long phonenum = input.nextLong();
list.add(name);
list.add(age);
list.add(phonenum);
System.out.println("Enter 'Y' to continue, 'N' to Stop: ");
input.nextLine();
stop = input.nextLine().charAt(0);
}
System.out.println(list);
}
}
possibility : 2
import java.util.*;
public class Naddy {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
char stop = 'Y';
LinkedList<User> list = new LinkedList<User>();
while (stop != 'N') {
System.out.println("\nEnter your name : ");
String name = input.nextLine();
System.out.println("\nEnter your age: ");
int age = input.nextInt();
System.out.println("\nEnter your phone number: ");
long phonenum = input.nextLong();
list.add(new User(name, age, phonenum));
System.out.println("Enter 'Y' to continue, 'N' to Stop: ");
input.nextLine();
stop = input.nextLine().charAt(0);
}
System.out.println(list);
}
}
class User {
private String name;
private int age;
private long phonenum;
public User() {
}
public User(String name, int age, long phonenum) {
this.name = name;
this.age = age;
this.phonenum = phonenum;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public long getPhonenum() {
return phonenum;
}
public void setPhonenum(long phonenum) {
this.phonenum = phonenum;
}
#Override
public String toString() {
return "User [age=" + age + ", name=" + name + ", phonenum=" + phonenum + "]";
}
}

Constructor doesnt set any values

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.

String name is not getting printed

import java.util.*;
//student class
class Student{
String name;
int rollNo;
Student(String name, int rollNo){
this.name=new String(name);
this.rollNo=rollNo;
}
}
class Demo {
public static void main (String[] args) {
Scanner in = new Scanner(System.in);
int x = in.nextInt();
int noOfStudents = in.nextInt();
Student[] StudentList= new Student[noOfStudents];
PriorityQueue<Student> set=new PriorityQueue<Student>(new Comparator<Student>(){
public int compare(Student a, Student b){
return b.rollNo-a.rollNo;
}
});
for(int i=0;i<noOfStudents;i++){
String name = in.nextLine();
in.nextLine();
int rollNo = in.nextInt();
set.add(new Student(name,rollNo));
}
while(!set.isEmpty()){
Student tmp = set.poll();
System.out.println(tmp.name+" "+tmp.rollNo);
}
}
}
I am trying to take n students name and roll no and then printing it. But this is not printing the names of student
I have added the extra nextline() to enable integer entry
I always feel difficulty in this thing. Please help!
Replace
String name = in.nextLine();
in.nextLine();
int rollNo = in.nextInt();
by
in.nextLine();
String name = in.nextLine();
int rollNo = in.nextInt();
You can find the full explanation of your issue here : https://www.geeksforgeeks.org/why-is-scanner-skipping-nextline-after-use-of-other-next-functions/
Change:
String name = in.nextLine();
in.nextLine();
int rollNo = in.nextInt();
to
String name = in.next();
int rollNo = in.nextInt();
I think this version works as you can see from the picture. I added this line:
in.nextLine(); // it consumes the newline and moves to the starting of the next line.
Here's the code:
import java.util.*;
//student class
class Student{
String name;
int rollNo;
Student(String name, int rollNo){
this.name=new String(name);
this.rollNo=rollNo;
}
}
public class Main {
public static void main (String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Inert the number of students, please");
int noOfStudents = in.nextInt();
Student[] StudentList= new Student[noOfStudents];
PriorityQueue<Student> set=new PriorityQueue<Student>(new Comparator<Student>(){
public int compare(Student a, Student b){
return b.rollNo-a.rollNo;
}
});
for(int i=0;i<noOfStudents;i++){
in.nextLine(); // it consumes the newline and moves to the starting of the next line.
System.out.println("Enter the student's name "+i);
String name = in.nextLine();
System.out.println("Enter the student ID number "+i);
int rollNo = in.nextInt();
set.add(new Student(name,rollNo));
}
while(!set.isEmpty()){
Student tmp = set.poll();
System.out.println(tmp.name.toString()+" "+tmp.rollNo);
}
}
}
Execution of Java program
Best regards from Italy.

Java arrayList comparison

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;
}
});

Categories