Java arrayList comparison - java

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

Related

Collections.sort() error occuring while sorting ArrayList [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I'm trying to sort by name ArrayList elements but I couldn't solve problem . . . . . .
Could someone help?
ERROR At case 4: Collections.sort(contact);
ERROR "Required type: List Provided: List reason: no
instance(s) of type variable(s) T exist so that Data conforms to
Comparable<? super T>"
below code works fine without sort
public class AddressBook {
private static List<Data> contact = new ArrayList<Data>();
public static void main(String[] args) {
AddressBook addressBook = new AddressBook();
Scanner sc = new Scanner(System.in);
int menu;
String choice;
String choice2;
System.out.println(" =========================== ");
System.out.println(" | 0. Exit. |");
System.out.println(" | 1. Add contact. |");
System.out.println(" =========================== ");
try
{
menu = sc.nextInt();
while (menu != 0) {
switch (menu) {
case 1:
while (menu != 2) {
System.out.println("Enter First Name: ");
String firstName = sc.next();
System.out.println("Enter Last Name: ");
String lastName = sc.next();
System.out.println("Enter Phone: ");
String homePhone = sc.next();
if (homePhone.length()!=11 || !homePhone.startsWith("8")) {
System.out.println("Number should start with '8' and has '11' digit" );
}else {
System.out.println("Enter Email: ");
String personalWebSite = sc.next();
contact.add(new Data(firstName, lastName,
homePhone, personalWebSite));
}
System.out
.println("Would you like to add someone else? 1: Yes, 2: No");
menu = sc.nextInt();
}
break;
case 2:
System.out
.println("Enter First Name of contact that you would like to edit: ");
choice = sc.next();
addressBook.deleteByFirstName(choice);
System.out.println("Enter First Name: ");
String firstName = sc.next().toUpperCase();
System.out.println("Enter Last Name: ");
String lastName = sc.next();
System.out.println("Enter Phone: ");
String homePhone = sc.next();
System.out.println("Enter Email: ");
String personalWebSite = sc.next();
contact.add(new Data(firstName, lastName,
homePhone, personalWebSite));
break;
case 3:
System.out.println("------------------");
System.out.println("1. Search number: ");
System.out.println("2. Search name: ");
System.out.println("------------------");
int search= sc.nextInt();
if(search==1) {
System.out
.println("Enter Number of contact: ");
choice2 = sc.next();
addressBook.searchByPhoneNumber(choice2);
break;
}else {
System.out
.println("Enter First Name of contact: ");
choice = sc.next();
addressBook.searchByFirstName(choice);
break;
}
case 4:
Collections.sort(contact);
//ERROR occurring here
case 5:
System.out.println("This is a list of every contact");
System.out.println(addressBook.contact);
break;
case 6:
System.out.println("------------------");
System.out.println("1. Delete by name: ");
System.out.println("2. Delete all: ");
System.out.println("------------------");
int del= sc.nextInt();
if(del==1){
System.out
.println("Enter First Name of contact that you would like to delete: ");
choice = sc.next();
addressBook.deleteByFirstName(choice);
break;
}else{
System.out.println("Successfully Deleted");
System.out.println("");
contact.clear();
}
break;
default:
throw new IllegalStateException("Unexpected value: " + menu);
}
System.out.println(" =========================== ");
System.out.println(" | 0. Exit. |");
System.out.println(" | 1. Add contact. |");
System.out.println(" =========================== ");
menu = sc.nextInt();
}
}
catch(InputMismatchException exception)
{
System.out.println("This is not an integer");
}
System.out.println("Good-Bye!");
}
private void searchByFirstName(String firstName) {
for (Iterator<Data> iterator = contact.iterator(); iterator.hasNext();) {
Data temp = iterator.next();
if (temp.getFirstName().equalsIgnoreCase(firstName)) {
System.out.println(temp);
return;
}
}
System.out.println("No contact with first name " + firstName
+ " was found.");
}
private void searchByPhoneNumber(String homePhone) {
for (Iterator<Data> iterator = contact.iterator(); iterator.hasNext();) {
Data temp = iterator.next();
if (temp.getHomePhone().equalsIgnoreCase(homePhone)) {
System.out.println(temp);
return;
}
}
System.out.println("No contact with number " + homePhone
+ " was found.");
}
private void deleteByFirstName(String firstName) {
for (Iterator<Data> iterator = contact.iterator(); iterator.hasNext();) {
Data temp = iterator.next();
if (temp.getFirstName().equalsIgnoreCase(firstName)) {
iterator.remove();
return;
}
}
System.out.println("No contact with first name " + firstName
+ " was found.");
}
private void deleteAll(String all) {
for (Iterator<Data> iterator = contact.iterator(); iterator.hasNext();) {
iterator.remove();
return;
}
System.out.println("Deleting...");
}
private static int[] selectionSortAlg(int[] a, int n) {
for (int i = 0; i < n - 1; i++) {
int iMin = i;
for (int j = i + 1; j < n; j++) {
if (a[j] < a[iMin]) {
iMin = j; // index of smallest element
}
}
int temp = a[i];
a[i] = a[iMin];
a[iMin] = temp;
System.out.println("Pass..." + i + "..." + Arrays.toString(a));
}
return a;
}
public static class Data {
private String firstName = null;
private String lastName = null;
private String homePhone = null;
private String personalWebSite = null;
public Data(String firstName,String lastName, String homePhone, String personalWebSite) {
this.firstName = firstName;
this.lastName = lastName;
this.homePhone = homePhone;
this.personalWebSite = personalWebSite;
}
public String getFirstName() {
return firstName;
}
public String getHomePhone() {
return homePhone;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String toString() {
return String.format(firstName+" "+lastName+" "+homePhone+" "+personalWebSite);
}
}
}
class T {
private String firstName = null;
private String lastName = null;
private String homePhone = null;
private String personalWebSite = null;
public T(String firstName,String lastName, String homePhone, String personalWebSite) {
this.firstName = firstName;
this.lastName = lastName;
this.homePhone = homePhone;
this.personalWebSite = personalWebSite;
}
public String getFirstName() {
return firstName;
}
public String getHomePhone() {
return homePhone;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String toString() {
return String.format(firstName+" "+lastName+" "+homePhone+" "+personalWebSite);
}
}
I am not quite sure, but I think you need to do this(in your case 4):
Collections.sort(contact, new Comparator<Data>() {
#Override
public int compare(Data contact1, Data contact2) {
return contact1.getFirstName().compareTo(contact2.getFirstName());
}
});
Give it a try, I had used it somewhere else, and it worked. Hope it helps. Cheers :)
Use in this way
contact.sort( Comparator.comparing(Data::getFirstName) );
You have 2 options whether implement Comparable or provide comparator to sorting function, i.e.
Collections.sort(contact, (d1,d2) -> d1.firstName.compareTo(d2.firstName));
or
contact.sort((d1,d2) -> d1.firstName.compareTo(d2.firstName));
Your class Data you implement comparable, look at here:
https://www.geeksforgeeks.org/comparable-vs-comparator-in-java/
public static class Data implements Comparable<Data>
...
public int compareTo(Data m) {
...
}
Either pass a comparator in sort method or make Data class implement Comparable interface and implement compareTo()
#GiorgosDev gave an example in which data class is expected to implement comparable interface.
Either implement comparable in Data class or pass comparator in sort method. Example Collections.sort(contact, Comparator.comparing(Data::getFirstName));

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 Address Book String Reading

I have been having trouble with my removeContact method in the AddressBook class. I can get it to work when I enter a first name, but for some reason can't get it to work for the full name. This is probably simple but i'm just getting nowhere. Thanks
AddessBook Class
public class AddressBook {
private Contact contacts[] = new Contact[100]; //Array to hold all the contacts
private int count = 0; //Number of contacts in the array(in address book)
private String fileName;
AddressBook(String fileName){
this.fileName = fileName;
}
//Add Contact
public boolean addContact(Contact contact){
if(count<100){
contacts[count] = contact;
count++;
return true;
}else{
return false;
}
}
//Remove Contact
public boolean removeContact(String fullname){
for(int i = 0; i<count; i++){
if(fullname.equals(contacts[i].getFullName())){
for(int j = i; j<count; j++){
contacts[j] = contacts[j+1];
}
count--;
}else{
return false;
}
}
return true;
}
//Search Contact
//Display Contacts
public void displayContacts(){
for(int i = 0; i<count; i++){
System.out.println(contacts[i]);
}
}
}
Contact Class
public class Contact {
private String firstName;
private String lastName;
private String phone;
//Contact constructor
Contact(String firstName, String lastName, String phone){
this.firstName = firstName;
this.lastName = lastName;
this.phone = phone;
}
//First name getter
public String getFirstName(){
return firstName;
}
//Last name getter
public String getLastName(){
return lastName;
}
//Full name getter
public String getFullName(){
return firstName+" "+lastName;
}
//Phone number getter
public String getPhone(){
return phone;
}
//First name mutator
public void setFirstName(String firstName){
this.firstName = firstName;
}
//Last name mutator
public void setLastName(String lastName){
this.lastName = lastName;
}
//Phone number mutator
public void setPhone(String phone){
this.phone = phone;
}
//Method to compare first and last names for similarity
public boolean compare(Object o){
Contact contact = (Contact) o;
if(firstName == contact.firstName && lastName == contact.lastName){
return false;
}else{
return true;
}
}
public String toString(){
return firstName+" "+lastName+" "+phone;
}
}
Main Class
import java.util.*;
public class Main {
public static void main(String [] args){
AddressBook addressbook = new AddressBook("Info.txt");
Scanner s = new Scanner(System.in);
boolean quit = false;
while(!quit){
System.out.println("What would you like to do?");
System.out.println(" 1) Display all contacts");
System.out.println(" 2) Add a contact");
System.out.println(" 3) Remove a contact");
System.out.println(" 4) Search a contact");
System.out.println(" 5) Exit");
switch(s.nextInt()){
case 1:
addressbook.displayContacts();
break;
case 2:
System.out.println("First Name: ");
String fName = s.next();
System.out.println("Last Name: ");
String lName = s.next();
System.out.println("Phone Number: ");
String pNumber = s.next();
addressbook.addContact(new Contact(fName, lName, pNumber));
break;
case 3:
System.out.println("Enter in full name: ");
String fullname = s.next();
addressbook.removeContact(fullname);
break;
case 4:
System.out.println("Enter the name of the contact you are looking for: ");
case 5:
quit = true;
break;
}}}}
You are asking for the full name and then comparing it only with the first name:
if(fullname.equals(contacts[i].getFirstName())){
Just compare it with the full name...
When you make your call to the "removeContact" method, you are passing as parameter only the name, not the last name; let say you create the contact "John Doe". When you search for "John Doe" you pass "John" as the name to the method but "Doe" is the next token in the scanner, so when you try to do s.nextInt() you have a problem because "Doe" is not an int.
Also, your removeContact method is not gonna work when you have more than 1 contact. You are doing a return if the first contact of the address book is not the one you are looking for.
Edit:
Try this and let me know what happens:
case 3:
System.out.println("Enter in full name: ");
String firstName = s.next();
String lastName = s.next();
addressbook.removeContact(firstName + " " + lastName);
break;
Edit 2:
// Remove Contact
public boolean removeContact(String fullname) {
for (int i = 0; i < count; i++) {
// No need for an else here
if (fullname.equals(contacts[i].getFullName())) {
for (int j = i; j < count; j++) {
contacts[j] = contacts[j + 1];
}
count--;
return true;
}
}
return false;
}
Ok, I ran your code and tried to remove a name , so I got this error :
Exception in thread "main" java.util.InputMismatchException
Your remove method is not correct. You can easily have 17 Bob's in your Address Book - "Bob Smith", "Bob Jacobs", "Bob Ahmed" , whatever...
You need to fix the removeContact method to look more like this :
public boolean removeContact(String fname, String lname){
for(int i = 0; i<count; i++){
if(contacts[i].getFirstName().equals(fname) && contacts[i].getLastName().equals(lname)){
for(int j = i; j<count; j++){
contacts[j] = contacts[j+1];
}
Also, the case 3 of Main should lok like this :
case 3:
System.out.println("Enter in first name: ");
String firstname = s.next();
System.out.println("Enter in last name: ");
String lastname = s.next();
addressbook.removeContact(firstname, lastname);
break;

AddressBook Program Remove And Search Method Null Pointer Exceptions

EDIT5:My remove() method asks for a name to remove, and no matter what name I enter in it will delete the latest name in the array. I'm not sure how to fix this, and my search array will ask for a name and then declare a Null Pointer Exception error. The rest of my code is provided below.
case 3: //Remove a contact
System.out.print("Full name to remove: ");
Scanner rs = new Scanner(System.in);
String deleteName = rs.nextLine();
a1.remove(deleteName);
break;
case 4: //search a contact
System.out.print("Full name to search: ");
Scanner ss = new Scanner(System.in);
String searchName = ss.nextLine();
a1.search(searchName);
break;
EDIT4: Figured out the initialization problem.. can't believe I missed something so simple. My program now works nearly perfect, besides for my remove function, which encounters a null Pointer exception. Can someone explain to me why this happens? Also I've updated the code
EDIT3: I now have nothing yelling at me in my Contact and AddressBook classes. I just need to know how to make my methods in main work. As someone pointed out in the comments I need to initialize my methods and classes. Can someone please tell me where I need to put my constructor so these methods will work? I have them placed in multiple areas of my program already to no avail.
I'm working on an AddressBook program for my java class. I've constructed everything, but my methods in other classes are giving me some difficulty(I made all my methods public and my class specific variables private). Also I would like some feedback on how I constructed my methods. I was given a rough outline of what methods to use here:
Contact
-firstName:String
-lastName:String
-phone:String
+Contact(firstName:String,lastName:String, phone:String)
+getFullName():String
+getLastName():String
+getPhone():String
+setFirstName(firstName:String):void
+setLastName(lastName:String):void
+setPhone(phone:String):void
+equals(o:Object):boolean #currently not sure how to do this method
+toString():String
AddressBook class
-contacts:Contact[]
- count:int;
-fileName:String
+AddressBook(fileName:String)
+add(Contact c):boolean
+remove(fullName:String):boolean
+search(fullName:String):Contact
+display():void
+load():boolean
+save():boolean
+search(String fullName):boolean
Here is my code:
Contact class code:
public class Contact {
private String firstName;
private String lastName;
private String phone;
public Contact(String firstName, String lastName, String phone) {
this.firstName = firstName;
this.lastName = lastName;
this.phone = phone;
}
public String getFullName(){
return firstName + " " + lastName;
}
public String getFirstName(){
return firstName;
}
public String getLastName(){
return lastName;
}
public String getPhone(){
return phone;
}
public void setFirstName(String firstName){
this.firstName = firstName;
}
public void setLastName(String lastName){
this.lastName = lastName;
}
public void setPhone(String phone){
this.phone = phone;
}
/*public boolean equals(Contact o){ //not sure how to use this method, tips/suggestions?
}*/
public String toString(){
return firstName + ":" + lastName + ":" + phone;
}
}
AddressBook Class
import java.io.File;
import java.io.FileWriter;
import java.util.Scanner;
public class AddressBook {
private Contact[] contacts = new Contact[100];
private int count = 0;
private String fileName;
public AddressBook(String fileName) {
this.fileName = fileName;
}
public boolean add(Contact c) {
// Checks to see if the array is full
if (count > 99) {
return false;
}
// Adds the new contact into the array
contacts[count] = c;
// increment count
count++;
return true;
}
public boolean remove(String deleteName) { //switched fullName to deleteName to avoid duplicate variable problems
for (int i = 0; i < count; i++) {
if(contacts[i].getFullName() == deleteName) {
contacts[i] = null;
contacts[i] = contacts[i-1];
}
}
count--;
return true;
}
public Contact search(String searchName){ //switched fullName to searchName to avoid duplicate variable problems in the main class
for(int i = 0; i < contacts.length; i++){
if (contacts[i].getFullName() == searchName) {
return contacts[i];
}
} return null;
}
public void display() {
System.out.println("Name Phone Number"); //setting up the format for displaying contacts
System.out.println("-------------------------------");
for (int i = 0; i < count; i++) { //for loop printing out and displaying contacts
System.out.println(contacts[i].getFirstName() + " "
+ contacts[i].getLastName() + "\t\t"
+ contacts[i].getPhone());
}
System.out.println("-------------------------------");
}
public boolean load() {
//reads the file address.txt and loads it
try {
File fr = new File(fileName);
Scanner s = new Scanner(fr);
while(s.hasNextLine()) {
String oStore = s.nextLine(); //Storing the line of string here so it can be split
String[] aStore = oStore.split(":"); //Splits oStore up and inputs the values into constructor
contacts[count]=new Contact(aStore[0], aStore[1], aStore[2]);
count++;//increments count each contact
}
s.close();
return true;
} catch (Exception e){
return false;
}
}
public boolean save() {
// Writes the new contact into the file address.txt
try {
FileWriter fw = new FileWriter(fileName);
for (int i = 0; i < contacts.length; i++) {
fw.write(contacts[i].getFirstName() + ":"
+ contacts[i].getLastName() + ":"
+ contacts[i].getPhone() + "\n");
}
fw.close();
} catch (Exception e) {
return false;
}
return true;
}
/*public boolean search(String searchName) { //switched fullName to searchName to avoid duplicate variable problems in the main class
for(int i = 0; i <contacts.length; i++){
if (contacts[i].getFullName() == searchName) {
return contacts[i].getFullName() + contacts[i].getPhone();
}
}
return true;
}*/
}
Main Class
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
AddressBook a1 = new AddressBook("address.txt");
boolean pQuit = false; //boolean value to end the program
a1.load();
System.out.println("Welcome. Address book is loaded.");
System.out.println("");
do{
//Setting up the initial menu
System.out.println("What would you like to do?");
System.out.println("1) Display all contacts");
System.out.println("2) Add a contact");
System.out.println("3) Remove a contact");
System.out.println("4) Search a contact");
System.out.println("5) Exit");
System.out.println("Your choice: ");
Scanner s = new Scanner(System.in); //Scanner for user's choice
int choice = s.nextInt(); //User picks menu choice
System.out.println("\n");//line break
switch(choice){
case 1: //Display all contacts
a1.display();
break;
case 2: //Add a contact
System.out.print("First name:");
String firstName = s.next(); //Stores first name in firstName
System.out.print("Last name:");
String lastName = s.next(); //Stores last name in lastName
System.out.print("Phone number:");
String phone = s.next();
a1.add(new Contact(firstName,lastName,phone));
System.out.println("Contact added.");
break;
case 3: //Remove a contact
System.out.print("Full name to remove: ");
Scanner rs = new Scanner(System.in);
String deleteName = rs.nextLine();
a1.remove(deleteName);
break;
case 4: //search a contact
System.out.print("Full name to search: ");
Scanner ss = new Scanner(System.in);
String searchName = ss.nextLine();
a1.search(searchName);
break;
case 5: //exit the program
a1.save();
System.out.println("Addres book is saved to file.");
pQuit = true;
break;
default:
System.out.println("That is not a valid input.");
}
}while (pQuit == false);
}
}
Right now in my main method none of the methods I have called work because they are undefined. Same instance happened when I tried to use the contacts array in my +equals(o:Object):boolean method. All help is much appreciated, and if you see anything wrong in my methods or anything at all I could fix and improve please let me know!
Thanks in advance for the help.
EDIT1: Also please note the two search methods I was given. I pretty much constructed the same code for both. Eclipse right now is yelling at me telling me to change the name of the methods. I would like to know if I constructed the methods incorrectly, or why I would be given two of the same named methods to use in my program.
EDIT2: Updated to my new code. Changed a couple things, methods still do not work though.

ArrayList and sorting method for names

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

Categories