Java Converting do-while loop with while loop - java

I am implementing a simple sorting class, and was wondering how I would implement this using a while loop rather than a do-while loop.
The outer loop is executed once for each item in the ‘names’ list. However, it’s a do-while loop, which is always executed at least once. This will lead to an incorrect result if ‘names’ is the empty list. It should be replaced with a while loop.
SORT CLASS
public class Sort {
public static ArrayList<Name> sort1(ArrayList<Name> names) {
ArrayList<Name> results;
results = new ArrayList<Name>();
int count = names.size();
do {
Name firstName = new Name("zzz", "zzz");
for (Name name : names) {
if (name.getFirstName().compareTo(firstName.getFirstName()) < 0
|| name.getFirstName().equals(firstName.getFirstName())
&& name.getSurName().compareTo(firstName.getSurName()) < 0) {
firstName = new Name(name.getFirstName(), name.getSurName());
}
}
results.add(firstName);
names.remove(firstName);
count--;
} while (count > 0);
return results;
}}}
NAME CLASS
class Name {
String firstName;
String surName;
public Name() {
}
public Name(String firstName, String surName) {
this.firstName = firstName;
this.surName = surName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getSurName() {
return surName;
}
public void setSurName(String surName) {
this.surName = surName;
}
public String toString() {
return firstName + " " + surName;
}
public boolean equals(Object other) {
String fname = ((Name) other).firstName;
String sname = ((Name) other).surName;
if (firstName.equals(fname) && surName.equals(sname)) {
return true;
} else {
return false;
}
}

Just replace the do with your while (count > 0).

public class Sort {
private static void doIterate(List<Name> names, List<Name> results) {
Name firstName = new Name("zzz", "zzz");
for (Name name : names) {
if (name.getFirstName().compareTo(firstName.getFirstName()) < 0
|| name.getFirstName().equals(firstName.getFirstName())
&& name.getSurName().compareTo(firstName.getSurName()) < 0) {
firstName = new Name(name.getFirstName(), name.getSurName());
}
}
results.add(firstName);
names.remove(firstName);
}
public static ArrayList<Name> sort1(ArrayList<Name> names) {
ArrayList<Name> results;
results = new ArrayList<Name>();
int count = names.size();
doIterate(names, results);
count--;
while (count > 0) {
doIterate(names, results);
count--;
}
return results;
}}}

Since the while loop is always executed once, I would do a check prior to the loop to see if names has values in it. If yes, then do the do/while loop. Otherwise, skip it.

Related

How to Call a Method From Another Class, Through The Main Class?

Apologies for the poor title but I don't know how to phrase my issue. I am attempting to call the getSSN method from the Student class in my BubbleSorter class after a few students have been placed in an ArrayList. How can I call for the specific SSN variable. I understand why the error is occuring, but not how to change it to make it work. The error message is as follows: The method getSSN() is undefined for the type SearchandSort.
My Student Class:
public class Student {
private String firstName, lastName;
private int SSN;
public Student(String first, String last, int ssn) {
firstName = first;
lastName = last;
SSN = ssn;
}
public String toString() {
return lastName + ", " + firstName + " " + SSN + "\t";
}
public boolean equals(Object other) {
return (lastName.equals(((Student)other).getLastName()) && firstName.equals(((Student)other).getFirstName()) && (SSN == (((Student)other).getSSN())));
}
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 getSSN() {
return SSN;
}
public void setSSN(int SSN) {
this.SSN = SSN;
}
}
My BubbleSorter:
import java.lang.reflect.Array;
// “On my honor, I have neither received nor given any unauthorized assistance on this examination.”
public class BubbleSorter {
public static void bubbleSort(SortandSearch Students[]) {
int lastPos;
int index;
int temp;
for (lastPos = Students.length-1; lastPos >= 0; lastPos--) {
for (index = 0; index <= lastPos - 1; index++) {
if (((Students[index]).getSSN()) - ((Students[index+1].getSSN())) > 0) {
temp = Students[index].getSSN();
Students[index].getSSN() = Students[index+1].getSSN();
Students[index+1].getSSN() = temp;
}
}
}
}
}
My main class:
import java.util.ArrayList;
import java.util.Scanner;
public class SortandSearch {
public static void main(String[] args) {
Student a = new Student("Ryan", "Jones", 123456);
Student b = new Student("Jolie", "Decker", 123457);
ArrayList<Student> Students = new ArrayList<Student>();
Students.add(a);
Students.add(b);
System.out.println(Students);
bubbleSort(Students);
System.out.println(Students);
System.out.println("Please enter the SSN of the student you are searching for:");
Scanner scan = new Scanner(System.in);
int searchKey = scan.nextInt();
for (int index = 0; index < Students.size(); index++) {
if (Students.get(index).getSSN() == searchKey) {
System.out.print("The student with SSN " + searchKey + " is located at " + index);
}
}
}
}
EDIT:
The error now shows: The type of the expression must be an array type but it resolved to ArrayList.
New BubbleSorter:
import java.util.ArrayList;
// “On my honor, I have neither received nor given any unauthorized assistance on this examination.”
public class BubbleSorter {
public static void bubbleSort(ArrayList<Student> studentList) {
int lastPos;
int index;
int temp;
for (lastPos = studentList.size()-1; lastPos >= 0; lastPos--) {
for (index = 0; index <= lastPos - 1; index++) {
if ((studentList.get(index).getSSN()) - ((studentList.get(index).getSSN())) > 0) {
temp = studentList[index];
studentList[index] = studentList[index+1];
studentList[index+1] = temp;
}
}
}
}
}
There seem multiple things wrong to this code. I think you are trying unnessecary casting your arraylist to something else
First, I think your function signature should change to
public static void bubbleSort(ArrayList<Student> studentList)
And then you can access the elements with:
studentList.get(index).getSSN()
In SortandSearch you put instances of Student into ArrayList<>, and the your bubbleSort method must also take argument of this type or at least List and then convert it to array and return sorted list:
public static List<Student> bubbleSort(List<Student> studentsList) {
Student[] Students = studentsList.toArray(new Student[studentsList.size()]);
// ...
return Arrays.asList(Students);
}
And in the calling main method you need to store sorted list:
List<Student> sorted = BubbleSorter.bubbleSort(Students);
System.out.println(sorted);

Exception in thread "main" java.Lang.NullPointerException; unable to identify problem [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
Since I've finished my code I am debugging every step in the main. I keep hitting a NullPointerException not even 40 lines in. The problem is my setter is not working in my Person class. Or what I assume that my setter isn't working. But I also first believe my read isn't working for my file.
I've tried to change around the variables but I simply can't find the problem and why it won't add the name to the Person class. I read into NullPointerExceptions on here and can't find where that problem is for me to fix in my code.
public class Person {
private String firstName;
private String lastName;
private String address;
private String city;
private String state;
private String zipCode;
public Person(String firstName, String lastName, String address, String city, String state, String zipCode) {
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.city = city;
this.state = state;
this.zipCode = zipCode;
}
protected Person() {
}
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 String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return this.city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
#Override
public String toString() {
return "FirstName: " + firstName + "\nLastName: " + lastName + "\nAddress: " + address + "\nCity: " + city + "\nState: " + state + "\nZipCode: " + zipCode;
}
public String toCSV() {
return this.firstName + "," + this.lastName + "," + this.address + "," + this.city
+ "," + this.state + "," + this.zipCode;
}
public void copy(Person p) {
firstName = p.firstName;
lastName = p.lastName;
address = p.address;
city = p.city;
state = p.state;
zipCode = p.zipCode;
}
public void copy(String firstName, String lastName, String address, String city, String state, String zipCode) {
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.city = city;
this.zipCode = zipCode;
}
#Override
public Person clone() {
Person p = new Person(this.firstName, this.lastName, this.address, this.city, this.state, this.zipCode);
return p;
}
}
public class Customer extends Person{
private int customerID;
private double grossSales;
public Customer(int customerID, double grossSales, String firstName, String lastName, String address, String city, String state, String zipCode) {
super(firstName, lastName, address, city, state, zipCode);
this.customerID = customerID;
this.grossSales = grossSales;
}
public Customer(String s, int customerID, double grossSales, String firstName, String lastName, String address, String city, String state, String zipCode) {
super(firstName, lastName, address, city, state, zipCode);
copyCSV(s);
}
protected Customer() {
}
public int getCustomerID() {
return customerID;
}
public void setCustomerID(int customerID) {
this.customerID = customerID;
}
public double getGrossSales() {
return grossSales;
}
public void setGrossSales(double grossSales) {
this.grossSales = grossSales;
}
#Override
public String toString() {
return "CustomerID: " + customerID + "\nGrossSales: " + grossSales + super.toString();
}
public String toCSV() {
return this.customerID + "," + this.grossSales + "," + super.toCSV();
}
public void copy(Customer c) {
super.copy(c);
customerID = c.customerID;
grossSales = c.grossSales;
}
public void copy(int customerId, double grossSales, String firstName, String lastName, String address, String city, String state, String zipCode) {
super.copy(firstName, lastName, address, city, state, zipCode);
this.customerID = customerId;
this.grossSales = grossSales;
}
public Customer clone() {
Customer c = new Customer(this.customerID, this.grossSales, this.getFirstName(), this.getLastName(), this.getAddress(), this.getCity(), this.getState(), this.getZipCode());
return c;
}
public int compareTo(Customer c) {
int returnValue = 0;
if (this.customerID > c.customerID) {
returnValue = -1;
} else if (this.customerID < c.customerID) {
returnValue = 1;
} else {
returnValue = 0;
}
return returnValue;
}
public void copyCSV(String s) {
List<String> list = new ArrayList<>();
String[] a = s.split(",");
list = Arrays.asList(a);
this.copy(Integer.parseInt(list.get(0)), Double.parseDouble(list.get(1)), list.get(2),
list.get(3), list.get(4), list.get(5), list.get(6), list.get(7));
}
}
public class CustomerList {
public Customer[] cl;
public int size;
public CustomerList() {
this.cl = new Customer[4];
}
public int size() {
return this.size = cl.length;
}
public Customer get(Integer i) {
if (i < 0 || i >= size) {
throw new IndexOutOfBoundsException("null");
}
return cl[i];
}
public boolean set(Customer c,Integer i) {
if (i < 0 || i >= size) {
throw new IndexOutOfBoundsException("null");
} else {
cl[i] = c;
return true;
}
}
public void add(Customer c) {
for (int i = 0; i < size; i++) {
if (cl[i] == null) {
cl[i] = c;
} else {
if (i == size) {
Customer[] temp = new Customer[size * 2];
for (int j = 0; j < size; j++) {
temp[j] = cl[j];
}
cl[size] = c;
size++;
}
}
}
}
public Customer remove(Integer i) {
if (i < 0 || i >= size) {
throw new IndexOutOfBoundsException("null");
}
Customer temp = cl[i];
for (int j = 0; j < cl.length - 1; j++) {
cl[i] = cl[i + 1];
}
return temp;
}
#Override
public String toString() {
String s = " ";
double sum = 0;
for(Customer c: cl){
if(c == null)
s = "";
else
s += c + " \n";
}
for(Customer c: cl){
if (c == null)
sum += 0;
else
sum += c.getGrossSales();
}
return s + "\n" + "Total Gross Sales = " + Double.toString(sum);
}
public static CustomerList read(String fn) throws FileNotFoundException {
Scanner input = new Scanner(new File(fn));
CustomerList ab = new CustomerList();
try {
while(input.hasNextLine()) {
String currentline = input.nextLine();
Customer cd = new Customer();
cd.copyCSV(currentline);
cd.toCSV();
ab.add(cd);
}
} finally {
return ab;
}
}
//Write is facing the same problems as read. We can't access the toCSV() method from Customer.
public static boolean write(CustomerList cl, String fn) throws FileNotFoundException {
boolean a = false;
PrintWriter output = new PrintWriter(new File(fn));
// try {
for (int i = 0; i < cl.size; i++) {
Customer cd = new Customer();
cd.toCSV();
// }
// } catch (FileNotFoundException s) {
// System.out.println("File does not exist please try again: ");
// return a;
} return a = true;
}
//I utilized the sort function it said to and assume this will work as expected.
public void sort() {
Arrays.sort(cl);
}
public int indexOf(int id) {
for (int i = 0; i < size; i++) {
if(cl[i].getCustomerID() == id) {
return i;
}
}
return -1;
}
public boolean update(int id, double amt) {
boolean test;
int index = indexOf(id);
if(index == -1) {
System.out.println("CustomerID not present");
test = false;
} else {
amt += cl[index].getGrossSales();
test = true;
}
return test;
}
}
public static void main(String[] args) throws FileNotFoundException {
boolean b = false;
// Read file
System.out.println("Read file");
CustomerList cl = CustomerList.read("Customers.csv");
if(cl != null) {
System.out.println("Read: " + cl.size() + " records");
System.out.println(cl.toString() + "\n\n\n");
} else {
System.out.println("File read error.");
return;
}
// Test get and set for CustomerList
System.out.println("Test get and set for CustomerList");
System.out.println("x = " + cl.get(0));
Customer c = cl.get(0);
c.setFirstName("Homer"); // This is the line it keeps stopping at.
cl.set(c, 0);
System.out.println("x = " + cl.get(0));
System.out.println("\n\n\n");
It should be setting the first name of the customer as "Homer"
The only results it prints out is
Read file
Read: 4 records
Total Gross Sales = 0.0
Test get and set for CustomerList
x = null
--- Exception in thread "main" java.lang.NullPointerException
It's pretty simple, you ask to print cl.get(0). it returns null then you say Customer c = cl.get(0) which is null then you try to do c.setFirstName but c is null so nullPointerException.
Your are trying to access c but c is null. you need to initialize it as a new customer or make it equal to an actual customer (not null) before being able to setFirstName. Just do :
Customer c = new Customer();
c.setFirstName("homer");
It would work if your cl was not empty. To avoid this type of error you could also do :
Customer c;
if (cl.get(0) != null){
c = cl.get(0)
} else {
c = new Customer();
}
c.setFirstName("homer");

OOP parsing and adding object to list

So, I have three classes where the Class1 is used for different objects. In main class, the Class1 objects are made and names are set. Main class also makes new Household objects, the names are given to households and finally, persons are added to households as follows:
HouseholdOne.addPeopleToHousehold(person1);
The main class does not concern in present problem.
public class Class1 {
private String firstName;
private String middleName;
private String lastName;
public String setFirstName(String firstName) {
return this.firstName = firstName;
}
public String setLastName(String lastName) {
return this.lastName = lastName;
}
public String setMiddleName(String middleName) {
return this.middleName = middleName;
}
public String toString() {
if(firstName == "" && middleName == "" && lastName == "") {
return "";
} else if (firstName == null && middleName == null && lastName == null) {
return null;
} else
return firstName + " \"" + middleName + "\" " + lastName;
}
}
In the second class Household "addPeopleToHousehold" method the middle name of person should be parsed out from parameter and added to people list.
I had in mind to use .split function, but it does not work with object parameter.
How can I get given person middle name and
peopleList.add(personMiddleName)
Also in Household class, toString should print out household members like:
member1, member2, ... , memberx
public class Household {
List<Class1> peopleList = new ArrayList<>();
public String householdName;
public String setHouseholdName(String householdName) {
return this.householdName = householdName;
}
public void addPeopleToHousehold(Class1 people) {
// implementation needed //
}
public int getNumberOfPeople() {
return people.size();
}
public String toString() {
if (householdName == null || householdName == "") {
return "" + people;
}
return householdName + ": " + people;
}
}
Something like this perhaps? It was difficult to decipher your post, but the signature from the various methods says a lot. My changes simply adds people do the ArrayList peopleList. When you print the Household it will first check if a valid household name exists, after that it will loop each individual in the Household and add their full name to the list. The ((i + 1) != peopleList.size()) is only used to separate the names with a , except the last name.
Updated Class1. Fixed the setters and added a public getter for middle name.
public class Class1 {
private String firstName;
private String middleName;
private String lastName;
/*
* Setters
*/
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
/*
* Getters
*/
public String getMiddleName() {
return middleName;
}
/*
* toString
*/
public String toString() {
if(firstName == "" && middleName == "" && lastName == "") {
return "";
} else if (firstName == null && middleName == null && lastName == null) {
return null;
} else
return firstName + " \"" + middleName + "\" " + lastName;
}
}
Updated Household class. Various fixes:
public class Household {
List<Class1> peopleList = new ArrayList<>();
public String householdName;
public String setHouseholdName(String householdName) {
this.householdName = householdName;
}
public void addPeopleToHousehold(Class1 people) {
peopleList.add(people);
}
public int getNumberOfPeople() {
return peopleList.size();
}
public String toString() {
String returnString = "";
if (householdName != null) {
returnString = householdName + ": ";
}
// Loop the members
for (int i = 0; i < peopleList.size(); i++) {
returnString += peopleList.get(i).getMiddleName();
if ((i + 1) != peopleList.size()) {
returnString += ", ";
}
}
return returnString;
}
}
In addition to the answer of OptimusCrime, you might want to use StringBuilder instead of just using returnString += to append strings.
The drawback of using += to append strings is it will create new String objects whenever you append, so you will have greater memory consumption.

Scanner requesting multiple inputs before giving final output

So I'm new to Java and am trying to pass a variable from the scanner to my getter/setter method so that depending on the number entered it'll sort the array differently.
I've got it where the list will sort; problem is my scanner repeats where you have to enter your selection in multiple times before the list shows up.
I know the problem has to do with the call "int c = assign_6.choice()". If I hard code in a number it's fine but it appears to be making multiple calls to the choice() function.
I've tried moving the function out of the main and removing the Comparable in my setter/getter file and also removing the quick sort and using Array and Collections. None of which worked.
I feel like it's probably a stupid mistake I'm making and missing it due to not knowing Java that well. Could use help in figuring this out.
Here's my output:
nter number 1,2 or 3: 1
Enter number 1,2 or 3: 1
Enter number 1,2 or 3: 1
Enter number 1,2 or 3: 1
Enter number 1,2 or 3: 1
Enter number 1,2 or 3: 1
Enter number 1,2 or 3: 1
Enter number 1,2 or 3: 1
Enter number 1,2 or 3: 1
Enter number 1,2 or 3: 1
contacts [age=20, state=Alabama, firstname=Pickles, lastname=Cattle]
contacts [age=35, state=New York, firstname=George, lastname=Constanza]
contacts [age=90, state=Florida, firstname=Adam, lastname=Tree]
contacts [age=32, state=Illinois, firstname=Mary, lastname=Upton]
contacts [age=58, state=Washington, firstname=Bob, lastname=Wiseman]
Code:
import java.util.Scanner;
public class test_6 {
public static void main(String[] args) {
Contacts[] a = {
new Contacts(32, "Illinois", "Mary", "Upton"),
new Contacts(58, "Washington", "Bob", "Wiseman"),
new Contacts(20, "Alabama", "Pickles", "Cattle"),
new Contacts(35, "New York", "George", "Constanza"),
new Contacts(90, "Florida", "Adam", "Tree"),
};
Quick.sort(a);
for (Contacts contacts:a){
System.out.println(contacts);
}
}
public static int choice() {
System.out.print("Enter number 1,2 or 3: ");
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
return i;
}
}
public class Contacts implements Comparable<Contacts>{
Integer age;
String state;
String firstname;
String lastname;
int c = test_6.choice();
public Contacts(Integer age, String state, String firstname, String lastname){
this.age = age;
this.state = state;
this.firstname = firstname;
this.lastname = lastname;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
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 compareTo(Contacts contacts) {
if (c == 1){
return this.getLastname().compareTo(contacts.getLastname());
}
else if (c == 2){
return this.getState().compareTo(contacts.getState());
}
else if (c == 3){
return this.getAge().compareTo(contacts.getAge());
}
else return 0;
}
#Override
public String toString() {
return "contacts [age=" + age + ", state=" + state + ", firstname=" + firstname + ", lastname=" + lastname
+ "]";
}
}
I'm not entirely sure, you could debug, but it may be something to do with your function being assigned in the global scope. You are better to move the static function choice() to your Contacts class/object.
Then call the choice() function from inside the initializer Contacts. For example:
import java.util.Scanner;
public class test_6 {
public static void main(String[] args) {
Contacts[] a = {
new Contacts(32, "Illinois", "Mary", "Upton"),
new Contacts(58, "Washington", "Bob", "Wiseman"),
new Contacts(20, "Alabama", "Pickles", "Cattle"),
new Contacts(35, "New York", "George", "Constanza"),
new Contacts(90, "Florida", "Adam", "Tree"),
};
Quick.sort(a);
for (Contacts contacts:a){
System.out.println(contacts);
}
}
//Function Choice Moved to Contacts.choice()
}
public class Contacts implements Comparable<Contacts>{
Integer age;
String state;
String firstname;
String lastname;
int c;
public Contacts(Integer age, String state, String firstname, String lastname){
this.age = age;
this.state = state;
this.firstname = firstname;
this.lastname = lastname;
this.c = choice();
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
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 compareTo(Contacts contacts) {
if (c == 1){
return this.getLastname().compareTo(contacts.getLastname());
}
else if (c == 2){
return this.getState().compareTo(contacts.getState());
}
else if (c == 3){
return this.getAge().compareTo(contacts.getAge());
}
else return 0;
}
public static int choice() {
System.out.print("Enter number 1,2 or 3: ");
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
return i;
}
#Override
public String toString() {
return "contacts [age=" + age + ", state=" + state + ", firstname=" + firstname + ", lastname=" + lastname
+ "]";
}
}
I don't have enough rep to comment but I feel like it could be your sc.nextInt() statement. try to call sc.close() before you return I and see if that solves your problem.

Do I have to CompareTo implementation?

I am trying to search in a list but I sort as array so that I convert my linked list to array list but when I compile it without this part below. Command prompt gives "Person is not abstract and does not override abstract method compareTo(Person) in Comparable".
How can I fix this?
public int compareTo(Person other){
if (!this.name.equalsIgnoreCase(other.name))
return this.name.compareTo(other.name);
return this.name + " "+other.name;
}
Search list and sort methods:
public void searchList(String search)
{
if(phoneList.size() == 0){
System.out.println("There is no record phone book.");
}
Node<Person> tempNode = phoneList.head;
SLinkedList<Person> tempList = new SLinkedList();
for(int i=1; i<=phoneList.size; i++)
{
if (tempNode.getElement().getName().contains(search) || tempNode.getElement().getSurname().contains(search) || tempNode.getElement().getAddress().contains(search) || tempNode.getElement().getCell().contains(search) || tempNode.getElement().getHome().contains(search) || tempNode.getElement().getWork().contains(search))
{
tempList.addLast(tempNode.getElement());
personArray = new Person[tempList.size()];
Iterator<Person> it = tempList.iterator();
while(it.hasNext()){
int x = 0;
personArray[x] = it.next();
x++;
}
bubbleSort(personArray );
for(int x = 0; x < tempList.size(); x++)
System.out.println((x+1) + ""+ personArray[x]);
}
tempNode = tempNode.getNext();
}
}
public <AnyType extends Comparable<? super AnyType>> void bubbleSort(AnyType[] a) {
int outer, inner;
for (outer = a.length - 1; outer > 0; outer--) { // counting down
for (inner = 0; inner < outer; inner++) { // bubbling up
if (a[inner].compareTo(a[inner + 1]) > 0) { // if out of order...
//then swap
swapReferences(a,inner,inner+1);
}
}
}
}
public <AnyType> void swapReferences( AnyType [ ] a, int index1, int index2 )
{
AnyType tmp = a[ index1 ];
a[ index1 ] = a[ index2 ];
a[ index2 ] = tmp;
}
Person Class:
public class Person implements Comparable<Person>
{
private String name;
private String surname;
public String address;
public String cell;
public String home;
public String work;
public Person(String name, String surname, String address, String cell, String home, String work)
{
this.name = name;
this.surname = surname;
this.address = address;
this.cell = cell;
this.home = home;
this.work = work;
}
// Accessor methods:
public String getName(){
return name;
}
public String getSurname(){
return surname;
}
public String getAddress(){
return address;
}
public String getCell(){
return cell;
}
public String getHome(){
return home;
}
public String getWork(){
return work;
}
// Modifier methods:
public void setName(String name){
this.name = name;
}
public void setSurname(String surname){
this.surname = surname;
}
public void setAddress (String address){
this.address = address;
}
public void setCell (String cell){
this.cell = cell;
}
public void setHome (String home){
this.home = home;
}
public void setWork (String work){
this.work = work;
}
public String toString(){
return name + " " + surname + " " + address + " " + cell + " " + home + " " + work;
}
public int compareTo(Person other){
if (!this.name.equalsIgnoreCase(other.name))
return this.name.compareTo(other.name);
return this.name + " "+other.name;
}
}
Your existing compareTo method has a problem, but removing it violates the implements Comparable contract, since you must provide a compareTo method.
public int compareTo(Person other) {
if (!this.name.equalsIgnoreCase(other.name))
return this.name.compareTo(other.name);
// next line returns a String, but the method needs to return an int
return this.name + " " + other.name;
}
You can instead rely more directly on the standard String compareTo:
public int compareTo(Person other) {
if ( this.name.equalsIgnoreCase( other.name ) ) { return 0 };
return this.name.compareTo( other.name );
}
If you didn't have the ignore case constraint you've coded for, this would simply be
public int compareTo(Person other) {
return this.name.compareTo( other.name );
}
As an aside, there is no reason to make address, cell, home, and work public — and that's generally bad practice.
In order to implement an interface you need to implement all the methods in that interface. You either remove implements Comparable part or add public int compareTo method to your class.
The rule of compareTo method is that :
- if this Person is greater than other , return 1
- if this Person is smaller than other , return -1
- if they are equal, return 0

Categories