Find method in Linked List - java

I have a linked list with objects called ll. My object is called Student which has a name, a grade and an age. I want to create a find method based on the student's name.
import java.util.LinkedList;
import java.util.Scanner;
public class Course {
LinkedList<Object> ll = new LinkedList<Object>();
Scanner s = new Scanner(System.in);
public void addStudent() {
p("Enter the name that you want");
String f = s.nextLine();
Student a = new Student(f);
ll.add(a);
}
public void changeName() { //this method is to change the name of a student
Student student = findStudent();
p("Enter the name that you want");
String newName = s.nextLine();
Student.setName(newName);
}
public void setGrade() { //this method is to put the student's grade
Student student = findStudent();
p("Enter the grade that you want");
int grade = s.nextInt();
Student.setGrade(grade);
}
public void setAge() { //This method is to put the student's grade
Student student = findStudent();
p("Enter the age that you want");
int age = s.nextInt();
Student.setAge(age);
}
public Student findStudent(){
p("Which student do you want to change? Please enter their name:");
String name = s.nextLine();
boolean a=false;
for (int e=0; e<ll.size(); e++) {
if (name.equals(ll(e).name)) {
p("Found the student");
break;
return e;
//Find student in the list - left for the author
} else {
a=true;
}
}
if (a) {
p("Student is not in the list");
Student student = null;
return student;}
}
public String show() {
if (ll!=null) {
for (int i=0; i<ll.size(); i++) {
return "Student(name:" + name + ", age:" + age + ", grade:" + grade + ")";
}
} else {return "There are no students in the list";
}
}
//-------------------------------------------------------------------------
public void p(String x) {
System.out.println(x);
}
public static void main(String[] args) {
p("What do you want to do?");
Course course = new Course();
p("To add a student press 1");
p("To change the name of a student press 2");
p("To set the grade for a student press 3");
p("To set the age of a student press 4");
p("To find a student press 5");
p("To show the students press 6");
p("To get the age of a student press 7");
p("To get the grade of a student press 8");
int a = s.nextInt();
if (a==1) {
addStudent();
} else if (a==2) {
changeName();
}else if (a==3) {
setGrade();
}else if (a==4) {
setAge();
} else if (a==5) {
findStudent();
}else if (a==6) {
show();
} else if (a==7) {
getAge();
} else if (a==8) {
getGrade();
}
new Course();
}
}
In the find method, it says that it can not find the symbol ll(int). What can i do to make a find method based on a parameter of my Object.

To get the n'th element from a list, use the get method: ll.get(e) instead of ll(e).
On the other hand, you are iterating over the list, and it's more efficient to not call get repeatedly on a linked list. Instead you can do this:
int e = 0;
for (Student s: ll) {
if (name.equals(s.name)) ....
e++;
}

To make the existing method work, you need to change :
if (name.equals(ll(e).name)) {
to
if (name.equals(ll.get(e).name)) {
We need to use get() method to get an element from a list, it's different from an array.
Also, if you want a method to find student by name, you can write one as follows:
public Student findStudent(String name){
for (int e=0; e<ll.size(); e++) {
if (ll.get(e).name.equals(name)) {
return e;
}
}
//Not found
return null;
}

Related

Why won't my array pass to the other class?

I have looked at similar examples or other programs that call array from another class and it seems like I have done it the correct way but I am still getting errors.
This is where the arrarys are stored:
import java.util.Scanner;
public class DriverProgram {
public static int[] IDs = new int[10];
public static String[] names = new String[10];
public static double[] grades = new double[10];
public static int i = 0;
static Student call = new Student();
public static void main(String[] args){
call = new Student();
Scanner command = new Scanner(System.in);
System.out.println("Please Enter a command(i, r, s, or d): ");
while(command.hasNext()){
char command1 = command.next().charAt(0);
if(command1 == 'i'){
call.AddToArray(IDs[], names[] , grades[], i);
}else if(command1 == 'r'){
call.RemoveFromArray(int [] IDs, String [] names,double [] grades, int i);
}else if(command1 == 's'){
call.SortArray(int [] IDs, String [] names,double [] grades, int i);
}else if(command1 == 'd'){
call.DisplayArray(int [] IDs, String [] names,double [] grades, int i);
}else if(command1 == 'z') {
break;
}
else System.out.println("Invalid command enter a valid command next time.");
System.out.println("Please Enter a command(i, r, s, or d) or z to finish: ");
}
}
And this is what I am tryign to call the arrays to:
import java.util.Scanner;
public class Student {
public static void AddToArray(int[] IDs, String[] names, double[] grades, int i) {
if (i >= 10) {
System.out.println("You have already inputted 10 students please delete one first.");
} else {
Scanner readin = new Scanner(System.in);
Scanner readinname = new Scanner(System.in);
Scanner readingrade = new Scanner(System.in);
System.out.println("Please enter student ID: ");
IDs[i] = readin.nextInt();
System.out.println("Please enter student name: ");
names[i] = readinname.nextLine();
System.out.println("Please enter student grade: ");
grades[i] = readingrade.nextDouble();
System.out.println(IDs[i] + " " + names[i] + " " + grades[i]);
i++;
for (int j = 0; j < i; j++) {
if (IDs[j] == IDs[i]) {
System.out.println("This student has already been entered.");
}else{
System.out.println("The student has been added");
break;
}
}
}
}
I am not sure what else I need or what I am missing in order to call those arrays.
call.AddToArray(IDs[], names[] , grades[], i);
should be replaced with
call.AddToArray(IDs, names , grades, i);
P.S. Design notes
Student has only static method, so this is utilitly class and should not allowed an instance creation
call.AddToArray() and others static methods should be called as Student.AddToArray()
array is not correct data strucutre where you can add or remove elements. There're more suitable data structures like List or Map.
It's better to use only one instance of Scanner.
This is how you DriverProgram could look like.
public class DriverProgram {
public static void main(String[] args) {
Map<Integer, Student> students = new HashMap<>();
Scanner scan = new Scanner(System.in);
while (scan.hasNext()) {
System.out.println("Please Enter a command [1-5]:");
System.out.println("1. add new student");
System.out.println("2. remove existed student");
System.out.println("3. sort existed students by grades desc");
System.out.println("4. show existed students");
System.out.println("5. exit");
System.out.print("> ");
int menu = scan.nextInt();
if (menu == 1)
addStudent(scan, students);
else if (menu == 2)
removeStudent(scan, students);
else if (menu == 3)
sortStudents(students);
else if (menu == 4)
showStudents(students);
else if (menu == 5)
break;
System.err.println("Unknown command. Try again");
}
}
private static void addStudent(Scanner scan, Map<Integer, Student> students) {
if (students.size() == 10) {
System.err.println("You have already inputted 10 students please delete one first.");
return;
}
System.out.print("Please enter student ID: ");
int id = scan.nextInt();
if (students.containsKey(id)) {
System.err.println("This student with this id has already been entered.");
return;
}
System.out.print("Please enter student name: ");
String name = scan.nextLine();
System.out.print("Please enter student grade: ");
double grade = scan.nextDouble();
students.put(id, new Student(id, name, grade));
}
private static void removeStudent(Scanner scan, Map<Integer, Student> students) {
}
private static void sortStudents(Map<Integer, Student> students) {
}
private static void showStudents(Map<Integer, Student> students) {
}
public static final class Student {
private final int id;
private final String name;
private final double grade;
public Student(int id, String name, double grade) {
this.id = id;
this.name = name;
this.grade = grade;
}
}
}

HashMap returning null after adding values

I know this question has been asked before but I can't understand how to fix this issue. I'm adding values to a HashMap and in setStudent and then when I try to change the value in replaceName but the key doesn't seem to exist.
import java.util.*;
public class Student {
private HashMap<String, List<String>> studentDetails = new HashMap<String, List<String>>();
private HashMap<String, List<String>> studentModules = new HashMap<String, List<String>>();
public void setStudent(String id, String name, String postalAddress, String emailAddress, String degreeTitle, String dateEnrolled, List<String> modules) {
List<String> information = new ArrayList<>();
information.add(name);
information.add(postalAddress);
information.add(emailAddress);
information.add(degreeTitle);
information.add(dateEnrolled);
studentDetails.put(id, information);
studentModules.put(id, modules);
}
public List<String> getStudentDetails(String x) {
return studentDetails.get(x);
}
public List<String> getStudentModules(String x) {
return studentModules.get(x);
}
public void replaceName(String id, String name, String postalAddress, String emailAddress, String degreeTitle, String dateEnrolled) {
List<String> information = new ArrayList<>();
information.add(name);
information.add(postalAddress);
information.add(emailAddress);
information.add(degreeTitle);
information.add(dateEnrolled);
studentDetails.replace(id, information);
}
}
My main class is quite long but basically it takes user input to get the values:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner source = new Scanner(System.in);
RecordManager r = new RecordManager();
Module m = new Module();
Student s = new Student();
ChangeName c = new ChangeName();
while (true) {
System.out.println("Please enter the student id:");
r.setId(source.nextLine());
System.out.println("Please enter the student name:");
r.setName(source.nextLine());
System.out.println("Please enter the student address:");
r.setAddress(source.nextLine());
System.out.println("Please enter the student email address:");
r.setEmailAddress(source.nextLine());
System.out.println("Please enter the degree title:");
r.setDegreeTitle(source.nextLine());
System.out.println("Please enter the date enrolled:");
r.setDateEnrolled(source.nextLine());
List<String> a = new ArrayList<>();
while (true) {
System.out.println("Please enter the module name:");
String name = source.nextLine();
m.setName(name);
a = r.addModule(name, a);
m.setTitle(name);
System.out.println("Please enter the module code:");
m.setCode(source.nextLine());
while (true) {
System.out.println("Please enter the module mark (between 1 and 100):");
int mark = source.nextInt();
if (mark > 0 && mark <101) {
m.setMark(mark);
break;
}
else {
System.out.println("Module mark must be between 1 and 100");
}
}
System.out.println("Please enter the module credits:");
m.setCredits(source.nextInt());
m.setModule();
System.out.println("Would you like to enter another module? (Y/N)");
String more = source.next();
if (more.equalsIgnoreCase("N")) {
break;
}
source.nextLine();
}
r.setModules(a);
s.setStudent(r.getId(), r.getName(), r.getAddress(), r.getEmailAddress(), r.getDegreeTitle(), r.getDateEnrolled(), r.getModules());
r.addStudents(r.getId(), s.getStudentDetails(r.getId()));
System.out.println("Would you like to enter the details for another student? (Y/N)");
String another = source.next();
if (another.equalsIgnoreCase("N")) {
break;
}
source.nextLine();
}
while (true) {
System.out.println("Full list of students and details (1) \nLookup a student by name (2) \nChange student name (3)");
source.nextLine();
int choice = source.nextInt();
if (choice == 1) {
for (String id : r.getStudents().keySet()) {
System.out.println(s.getStudentDetails(id) + " " + s.getStudentModules(id));
}
break;
}
else if (choice == 2) {
System.out.println("Please enter the full name of the student:");
source.nextLine();
String name = source.nextLine();
boolean exists = false;
int i = 0;
for (String id : r.getStudents().keySet()) {
if (s.getStudentDetails(id).get(i).equalsIgnoreCase(name)) {
System.out.println(s.getStudentDetails(id) + " " + s.getStudentModules(id));
exists = true;
}
i += 1;
}
if (exists == false) {
System.out.println("Student not found");
}
break;
}
else if (choice == 3) {
System.out.println("Please enter the ID of the student:");
source.nextLine();
String id = source.nextLine();
System.out.println("Please enter the new name:");
String name = source.nextLine();
c.changeName(id, name, s.getStudentDetails(id));
System.out.println(s.getStudentDetails(id));
break;
}
else {
System.out.println("Incorrect selection. Please enter 1, 2 or 3");
}
}
}
}
And finally I have the class to change the name:
import java.util.*;
public class ChangeName {
RecordManager r = new RecordManager();
Student s = new Student();
public void changeName(String id, String newName, List<String> details) {
s.replaceName(id, newName, details.get(1), details.get(2), details.get(3), details.get(4));
}
}
Any help would be greatly appreciated!!

Creating transcripts in java using array

so im very new to programming so sorry if is an inane question
But i have been given a homework where i have to create a transcript with java using array,
first i have to enter the students name and code, then the peogram should tell me to enter each lesson’s grade individually
And the result should display the student’s name,code and the grades i have entered for each lecture
I know how to enter make the program prompt me with each lecture and grade entry but showing all the grades i have entered next to thier lecture is what im stuck on
I would highly appreciate it if i get an answer.
Thanks
Take a look at this code, if there is something obscure, ask for clarification.
MainClass.java class
public class MainClass {
static boolean flag = true;
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {
//create new student
Student student = new Student();
//print out enter name of a student
System.out.println("Enter name of student: ");
//read students name from next line
student.setNameOfStudent(keyboard.nextLine());
//print out enter code of a student
System.out.println("Enter code of student: ");
//read students password from a next line
student.setPasswordOfStudent(keyboard.nextLine());
//create a list of lectures to add them to a student
List<Lecture> lectures = new ArrayList<>();
//do adding lectures and grades for them while N is not pressed
do {
// enter new lecture name
System.out.println("Add a lecture? Y or N ");
//take answer for adding a lecture from a next input
String answerForAddingLecture = keyboard.next();
//if answer is yes
if ("Y".equalsIgnoreCase(answerForAddingLecture)) {
// print enter a name of a lecture
System.out.println("Enter a name of a lecture? ");
//take a lecture name from next input
String lectureName = keyboard.next();
// create a lecture
Lecture lecture = new Lecture();
// set lecture name from lectureName variable
lecture.setNameOfLecture(lectureName);
//create a list of grades
List<Grade> listOfGrades = new ArrayList<>();
//do inside brackets while flag is set to true
do {
//print Add a grade for this lecture? Y or N
System.out.println("Add a grade for this lecture? Y or N ");
//set an answer variable from the next input
String answer = keyboard.next();
//if answer is yes
if ("Y".equalsIgnoreCase(answer)) {
//print what grade is it going to be?
System.out.println("What grade is it going to be?");
//create new grade object
Grade grade = new Grade();
//set temp variable to next int input
int temp = keyboard.nextInt();
//set grade value to the value of temp variable
grade.setGrade(temp);
// add this grade to a list of grades
listOfGrades.add(grade);
}
//if answer is negative
else if ("N".equalsIgnoreCase(answer)) {
//set flag to false
flag = false;
}
}
//do above as long as flag is set to true
while (flag);
//reset flag to true again for keep adding new lectures
flag = true;
//set a list of grades to a lecture grades list
lecture.setGradesOfLecture(listOfGrades);
//set a lecture to a list of lectures
lectures.add(lecture);
//set a list of lectures to a students lecture list
student.setLecturesOfStudent(lectures);
}
//if answer is negative
else if ("N".equalsIgnoreCase(answerForAddingLecture)) {
flag = false;
}
} while (flag);
//print a student with all lectures and grades
System.out.println(student.toString());
}
}
Student.java class
public class Student {
private String nameOfStudent;
private String passwordOfStudent;
private List<Lecture> lecturesOfStudent;
public Student() {
}
public Student(String nameOfStudent, String passwordOfStudent, List<Lecture> lecturesOfStudent) {
this.nameOfStudent = nameOfStudent;
this.passwordOfStudent = passwordOfStudent;
this.lecturesOfStudent = lecturesOfStudent;
}
/**
* #return the nameOfStudent
*/
public String getNameOfStudent() {
return nameOfStudent;
}
/**
* #param nameOfStudent the nameOfStudent to set
*/
public void setNameOfStudent(String nameOfStudent) {
this.nameOfStudent = nameOfStudent;
}
/**
* #return the passwordOfStudent
*/
public String getPasswordOfStudent() {
return passwordOfStudent;
}
/**
* #param passwordOfStudent the passwordOfStudent to set
*/
public void setPasswordOfStudent(String passwordOfStudent) {
this.passwordOfStudent = passwordOfStudent;
}
/**
* #return the lecturesOfStudent
*/
public List<Lecture> getLecturesOfStudent() {
return lecturesOfStudent;
}
/**
* #param lecturesOfStudent the lecturesOfStudent to set
*/
public void setLecturesOfStudent(List<Lecture> lecturesOfStudent) {
this.lecturesOfStudent = lecturesOfStudent;
}
public String getLecturesWithGrades() {
String temp = "\nLectures:";
for (Lecture l : getLecturesOfStudent()) {
temp += "\n" + l.getNameOfLecture();
temp += "\nGrades:\n";
for (Grade g : l.getGradesOfLecture()) {
temp += g.getGrade() + " ";
}
}
return temp;
}
#Override
public String toString() {
return "Student: " + getNameOfStudent() + " with a code: " + getPasswordOfStudent() + getLecturesWithGrades();
}
}
Lecture.java class
public class Lecture {
private String nameOfLecture;
private List<Grade> gradesOfLecture;
public Lecture() {
}
public Lecture(String nameOfLecture, List<Grade> gradesOfLecture) {
this.nameOfLecture = nameOfLecture;
this.gradesOfLecture = gradesOfLecture;
}
public String getNameOfLecture() {
return nameOfLecture;
}
public List<Grade> getGradesOfLecture() {
return gradesOfLecture;
}
public void setNameOfLecture(String nameOfLecture) {
this.nameOfLecture = nameOfLecture;
}
public void setGradesOfLecture(List<Grade> gradesOfLecture) {
this.gradesOfLecture = gradesOfLecture;
}
#Override
public String toString() {
return getNameOfLecture() + " " + getGradesOfLecture();
}
}
Grade.java class
/**
* Might add remarks on grades or any other properties some time later, therefore new
* object is created called Grade.
* #author
*/
public class Grade {
int grade;
public Grade() {
}
public Grade(int grade) {
this.grade = grade;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
#Override
public String toString() {
return getGrade() + " ";
}
}

ArrayLists (Removing and Changing Elements)

Hello everyone I am an amateur in Java and had some specific questions about a program using ArrayLists. The program is made up of several classes, and its purpose is to add, change, remove, and display friends from a Phone Book. I have the add and display methods done, but I'm having trouble with the remove and change method. I saw a similar case on this site, but it did not help me solve my problems. Any help at all would be much appreciated. This is what I have so far:
package bestfriends;
import java.util.Scanner;
import java.util.ArrayList;
public class BFFHelper
{
ArrayList<BestFriends> myBFFs;
Scanner keyboard = new Scanner(System.in);
public BFFHelper()
{
myBFFs = new ArrayList<BestFriends>();
}
public void addABFF()
{
System.out.println("Enter a first name: ");
String firstName = keyboard.next();
System.out.println("Enter a last name: ");
String lastName = keyboard.next();
System.out.println("Enter a nick name: ");
String nickName = keyboard.next();
System.out.println("Enter a phone number: ");
String cellPhone = keyboard.next();
BestFriends aBFF = new BestFriends(firstName, lastName, nickName, cellPhone);
myBFFs.add(aBFF);
}
public void changeABFF()
{
System.out.println("I am in changeBFF");
}
public void displayABFF()
{
System.out.println("My Best Friends Phonebook is: ");
System.out.println(myBFFs);
}
public void removeABFF()
{
System.out.print("Enter a friend's name to be removed: ");
int i = 0;
boolean found = false;
while (i < myBFFs.size() && !found)
{
if(firstName.equalsIgnoreCase(myBFFs.get(i).getFirstName()) && lastName.equalsIgnoreCase(myBFFs.get(i).getLastName()))
{
found = true;
}
else
i++;
}
}
}
That was my Helper Class, for which I'm having trouble with the removeABFF method, and still need to create a changeABFF method from scratch. Next is my main class:
package bestfriends;
import java.util.Scanner;
public class BFFPhoneBook
{
public static void main(String args[])
{
int menuOption = 0;
Scanner keyboard = new Scanner(System.in);
BFFHelper myHelper = new BFFHelper();
do
{
System.out.println("1. Add a Friend");
System.out.println("2. Change a Friend");
System.out.println("3. Remove a Friend");
System.out.println("4. Display a Friend");
System.out.println("5. Exit");
System.out.print("Enter your selection: ");
menuOption = keyboard.nextInt();
switch (menuOption)
{
case 1:
myHelper.addABFF();
break;
case 2:
myHelper.changeABFF();
break;
case 3:
myHelper.removeABFF();
break;
case 4:
myHelper.displayABFF();
break;
case 5:
break;
default:
System.out.println("Invalid option. Enter 1 - 5");
}
} while (menuOption != 5);
}
}
This is my last class:
package bestfriends;
public class BestFriends {
private static int friendNumber = 0;
private int friendIdNumber;
String firstName;
private String lastName;
private String nickName;
private String cellPhoneNumber;
public BestFriends (String aFirstName, String aLastName, String aNickName, String aCellPhone)
{
firstName = aFirstName;
lastName = aLastName;
nickName = aNickName;
cellPhoneNumber = aCellPhone;
friendIdNumber = ++friendNumber;
// friendIdNumber = friendNumber++;
}
public boolean equals(Object aFriend)
{
if (aFriend instanceof BestFriends )
{
BestFriends myFriend = (BestFriends) aFriend;
if (lastName.equals(myFriend.lastName) && firstName.equals(myFriend.firstName))
return true;
else
return false;
}
else
return false;
}
public String getFirstName()
{
return firstName;
}
public String getLastName()
{
return lastName;
}
public String getNickName()
{
return nickName;
}
public String getCellPhone()
{
return cellPhoneNumber;
}
public int getFriendId()
{
return friendIdNumber;
}
public String toString()
{
return friendIdNumber + ". " + firstName + " (" + nickName + ") " + lastName + "\n" + cellPhoneNumber + "\n";
}
}
To explore and manipulate a arraylist an iterator is used
the object lacks the Setters
declare variables
ArrayList<BestFriends> myBFFs;
Scanner keyboard = new Scanner(System.in);
BestFriends best;
public BFFHelper()
{
myBFFs = new ArrayList<BestFriends>();
best= new BestFriends();
}
Delete
public void removeABFF()
{
System.out.print("Enter a friend's name to be removed: ");
String name= keyboard.next().toLowerCase();// entry name to be removed
Iterator<BestFriends> nameIter = myBFFs.iterator(); //manipulate ArrayList
while (nameIter.hasNext()){
best = nameIter.next(); // obtained object list
if (best.getNickName().trim().toLowerCase().equals(name)){ // if equals name
nameIter.remove(best); // remove to arraylist
}
}
}
Update
public void changeABFF()
{
System.out.print("Enter a friend's name to be change: ");
String name= keyboard.next().toLowerCase().trim();//entry name to be update
Iterator<BestFriends> nameIter = myBFFs.iterator();
while (nameIter.hasNext()){
best = nameIter.next();
if (best.getNickName().trim().toLowerCase().equals(name)){// if equals name
best.setNickName("NEW DATE");//update data with new data Setters
....
}
}
}
In your remove method you do not accept any input of the values
public void removeABFF()
{
System.out.print("Enter a friend's name to be removed: ");
int i = 0;
boolean found = false;
while (i < myBFFs.size() && !found)
....
As you are using firstNamer and lastName to find the object you needs these values
System.out.println("Enter a first name: ");
String firstName = keyboard.next();
System.out.println("Enter a last name: ");
String lastName = keyboard.next();

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