toString Method Call in Java [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why is the toString() method being called when I print an object?
I have this piece of code below. I understand everything else except the output using the toString method in the Room Class . In the HotelMain Class, I just called the displayRooms Method that was in the Hotel Class. But, when I ran the program, the toString output was shown in the console.
If I'm right toString() is the textual representation of the value in the object. But, I'm not sure where I called the toString method.
Can someone solve my dilemma? Thank You.
Hotel Class
public class Hotel {
private String hotelName;
private Room[] rooms;
public Hotel(String hotelName, int numberOfRooms) {
this.hotelName = hotelName;
this.rooms = new Room[numberOfRooms];
}
public void addRooms(Room room) {
int position = -1;
for (int i = 0; i < this.rooms.length; i++) {
Room tempRoom = rooms[i];
if (tempRoom == null) {
position = i;
break;
}
}
if (position != -1) {
rooms[position] = room;
System.out.println("New room added at postion " + position);
} else {
System.out.println("Addition of room failed.");
}
}
public void displayRooms() {
System.out.println("The Hotel: " + this.hotelName + " has the following rooms.");
for (int i = 0; i < this.rooms.length; i++) {
Room tempRoom = rooms[i];
if (tempRoom != null) {
System.out.println(tempRoom);
}
}
}
Room Class
public class Room {
private int roomNumber;
private int numberOfBeds;
private boolean smokingOrNonSmoking;
public Room() {
}
public Room(int roomNumber, int numberOfBeds, boolean smokingOrNonSmoking) {
this.roomNumber = roomNumber;
this.numberOfBeds = numberOfBeds;
this.smokingOrNonSmoking = smokingOrNonSmoking;
}
#Override
public String toString() {
return "Room [roomNumber=" + roomNumber + ", numberOfBeds="
+ numberOfBeds + ", smokingOrNonSmoking=" + smokingOrNonSmoking
+ "]";
}
}
Hotel Main
public class HotelMain {
public static void main(String[] args) {
Hotel hotel = new Hotel("MahaRani Chain of Hotels", 10);
Room room1 = new Room(4, 2, true);
Room room2 = new Room(2, 1, false);
Room room3 = new Room(6, 3, true);
Room room4 = new Room(6, 4, false);
hotel.addRooms(room1);
hotel.addRooms(room3);
hotel.addRooms(room4);
hotel.addRooms(room2);
hotel.displayRooms();
}
}
Console

Room tempRoom = rooms[i];
if (tempRoom != null) {
System.out.println(tempRoom);
}
You have the above code in your displayRooms() method. It prints tempRoom, which is a reference of Room, and hence it calls toString() method overridden in the Room class.

when you call
System.out.println(tempRoom);
the toString() method of Room is automatically called on tempRoom.

In this line
System.out.println(tempRoom);
this is the same as
System.out.println(tempRoom.toString());

toString is a special method of the Object class, here is its description:
Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.
This method is widely used in those places when an object should be converted to textual representation. When you print an object to PrintStream (System.out in this case), this stream calls toString to convert this object to a string.

Related

Adding Created Object to ArrayList During Initialization - Java

in Java, I am creating a class, and I would like to keep track of all objects the are created in this class. I have implemented a way to store the names of each object (using ArrayList), but I cannot figure out how to store the object itself in the ArrayList. Here is a snippet of my code:
static public class Ship {
private static ArrayList<String> ships = new ArrayList<String>();
private static ArrayList<Ship> shipObs = new ArrayList<Ship>();
String name;
private ArrayList<String> cruises = new ArrayList<String>();
int maxPassengers;
private static final String[] CABINS = new String[] {"Balcony", "Ocean View", "Suite", "Interior"};
private int[] passengers = new int[] {0,0,0,0};
boolean inService = false;
public Ship(String name, int maxPassengers) {
// Ensure that each ship has a unique name
if (ships.size() == 0) {
this.name = name;
ships.add(name);
}
else if (ships.size() >= 1) {
for (int i=0; i < ships.size(); i++) {
if (ships.get(i).equals(name)) {
System.out.println("Ship "+name+" cannot be created because that name already exists");
return;
}
}
this.name = name;
ships.add(name);
}
this.maxPassengers = maxPassengers;
As you can see, I have the static ArrayList that I would like to populate with all created ships. I assume that this population would take place in the initializing function, but the only method for doing so that I can see would to do something like
shipObs.add(this);
But that doesn't work...
As pointed out in the comments to the question, in addition to the problem asked about, there is another problem: That is, the premature return inside the constructor. Both problems can be addressed by calling the constructor indirectly, through a static method.
import java.util.ArrayList;
public final class Ship {
// private static ArrayList<String> ships = new ArrayList<String>();
private static ArrayList<Ship> shipObs = new ArrayList<Ship>();
String name;
private ArrayList<String> cruises = new ArrayList<String>();
int maxPassengers;
private static final String[] CABINS =
new String[]{"Balcony", "Ocean View", "Suite", "Interior"};
private int[] passengers = new int[]{0, 0, 0, 0};
boolean inService = false;
private Ship(String name, int maxPassengers) {
this.name = name;
// shipObs.add (this);
this.maxPassengers = maxPassengers;
}
public static Ship createAShip(String name, int maxPassengers) {
for (int i = 0; i < shipObs.size(); i++) {
if (shipObs.get(i).name.equals(name)) {
System.out.println("Ship " + name
+ " cannot be created because that name already exists");
return shipObs.get(i);
}
}
Ship theShip = new Ship(name, maxPassengers);
ShipObs.add (theShip);
return theShip;
}
}
I made the constructor private. This prevents client code (code that uses the class) from calling the constructor, forcing use of the static method. But, this disables inheritance. To make it clear that inheritance is not allowed, I added final to public class Ship.
As stated in the comments to the question, a constructor should not return before construction of the Object is complete. If a constructor discovers it cannot be completed, an Exception needs to be thrown.
The static method first checks for a duplicate Ship name. If found, it returns the Ship that bears that name. It would be a good idea to change that part of the code to throw an exception. A third option is to have it return null. Whatever the choice, it should be made clear to users of the class. This can be done using Javadoc.
If a duplicate name is not found, a new Ship is created and returned.
I also simplified the code that checks for a duplicate name. If shipObs.size() returns zero, the for loop is not executed. It is not necessary to guard by enclosing within an if.
I also removed ArrayList<String> ships. Since an Object in shipObs has a name field, ArrayList<String> ships is redundant.
You can't just use a return in the constructor, that would just avoid the next parameter association, you needs to throw an error to stop the instanciation process
If you may need the full objects in a list, track them only with a List<Ship>
You'll the simplified if/else system, you can try to iterate over an empty, it doesn't matter, so just do it
class Ship {
private static List<Ship> ships = new ArrayList<>();
String name;
int maxPassengers;
public Ship(String name, int maxPassengers) {
this.name = name;
for (Ship ship : ships) {
System.out.println(ship + " " + ship.equals(this));
if (ship.equals(this)) {
String msg = "Ship " + ship.name + " cannot be created because that name already exists";
System.out.println(msg);
throw new IllegalArgumentException(msg);
}
}
ships.add(this);
this.maxPassengers = maxPassengers;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Ship ship = (Ship) o;
return name.equals(ship.name);
}
}
If you don't care about the full objects, just use a List<String>
private static List<String> shipNames = new ArrayList<>();
public Ship(String name, int maxPassengers) {
for (String ship : shipNames) {
if (ship.equals(name)) {
String msg = "Ship " + name + " cannot be created because that name already exists";
System.out.println(msg);
throw new IllegalArgumentException(msg);
}
}
this.name = name;
shipNames.add(name);
this.maxPassengers = maxPassengers;
}
The following code will throw the exception at the second line
Ship a = new Ship("ship_1", 10);
Ship b = new Ship("ship_1", 10);
Ship c = new Ship("ship_2", 10);

Referencing the array variables in the Reference class, sorting it using another method, and invoking the sorted values in the case statement

I am trying to call the array variables in the reference class, try to sort them using a user-defined method and call the method onto the case statement that will be invoked if the user chooses a particular number. I wanted to provide the user the option what attribute of a student will be sorted (i.e. name, course...) and show the sorted one dimensional array called in the case statements and invoked through the main method.
Here's the variables in the Reference class:
class RecordReference {
private int idNumber;
private String firstName = "";
private String middleName = "";
private String lastName = "";
private int age;
private String yearLevel;
private String course = "";
private double gwa;
public RecordReference(int i, String f, String m, String l, int a, String y, String c, double g) {
idNumber = i;
firstName = f;
middleName = m;
lastName = l;
age = a;
yearLevel = y;
course = c;
gwa = g;
}
public int getIdNumber() {
return idNumber;
}
public String getFirstName() {
return firstName;
}
public String getMiddleName() {
return middleName;
}
public String getLastName() {
return lastName;
}
public int getAge() {
return age;
}
public String getYearLevel() {
return yearLevel;
}
public String getCourse() {
return course;
}
public double getGwa() {
return gwa;
}
public void setIdNumber(int idnumber) {
idNumber = idnumber;
}
public void setFirstName(String fName) {
firstName = fName;
}
public void setMiddleName(String mName) {
middleName= mName;
}
public void setLastNameName(String lName) {
lastName= lName;
}
public void setAge(int a) {
age = a;
}
public void setYearLevel(String yLevel) {
yearLevel = yLevel;
}
public void setCourse(String c) {
course = c;
}
public void setGwa(int gwa) {
gwa = gwa;
}
public String toString() {
return String.valueOf(System.out.printf("%-15s%-15s%-15d%-15d%n",
firstName, course , yearLevel ,gwa));
}
} // end of class
And I am trying to call it in this sort method, but I don't know how to reference it.
public static void sortFirstNameArray(String[] f){
for (int i = 0; i < f.length - 1; i++) {
for (int j = i + 1; j < f.length; j++) {
if (f[i].compareToIgnoreCase(f[j]) > 0) {
String temp = f[i];
f[i] = f[j];
f[j] = temp;
}
}
}
}
After the sorting is successfully done, I'll call it in a switch case statements that will be invoked once the user chooses a particular number. This part has 5 case statements (Name, Age, Course, General Weighted Average and the option to sort it all - I plan to add more student attributes if this works)
(I don't know if I should store this in another method and call it in the main method or just put it in the main method like that)
public RecordReference Process(RecordReference[] f, RecordReference[] a) {
// for loop?
for (int x = 0; x < f.length; x++) {
switch (choice) {
case 1:
System.out.println("Sorted array of first name: ");
sortFirstNameArray(f[x].getFirstName());
System.out.printf("%-15s%n", Arrays.toString(f));
break;
case 2:
System.out.println("Sorted array of age: ");
// invokes the age method
sortAgeArray(a[x].getAge());
System.out.printf("%-15s%n", Arrays.toString(a));
break;
}
}
}
If it is in another method, what param do I include when I call it in the main method?
I tried this but it doesn't work, I don't know what to do
System.out.print("Please choose what student attribute you want to
sort :");
choice = keyboard.nextInt();
// calling the process method here, but I receive syntax error
Process(f,a); // Here, I want to pass the sorted values back into the array but I get an error.
If you can help me out that would be great. Thank you in advance.
I'm just a first year student and I am eager to learn in solving this error.
It's good to see that you have attempted the problem yourself and corrected your question to make it clearer, because of that I am willing to help out.
I have tried to keep the solution to the problem as close to your solution as possible, so that you are able to understand it. There may be better ways of solving this problem but that is not the focus here.
First of all, let's create a class named BubbleSorter that will hold methods for sorting:
public class BubbleSorter
{
//Explicitly provide an empty constructor for good practice.
public BubbleSorter(){}
//Method that accepts a variable of type RecordReference[], sorts the
//Array based on the firstName variable within each RecordReference
//and returns a sorted RecordReference[].
public RecordReference[] SortByFirstName(RecordReference[] recordReferencesList)
{
for (int i = 0; i < recordReferencesList.length - 1; i++) {
for (int j = i + 1; j < recordReferencesList.length; j++) {
if (recordReferencesList[i].getFirstName().compareToIgnoreCase
(recordReferencesList[j].getFirstName()) > 0) {
RecordReference temp = recordReferencesList[i];
recordReferencesList[i] = recordReferencesList[j];
recordReferencesList[j] = temp;
}
}
}
return recordReferencesList;
}
}
That gives us a class that we can instantiate, where methods can be added to be used for sorting. I have added one of those methods which takes a RecordReference[] as a parameter and sorts the RecordReference[] based on the firstName class variable within each RecordReference. You will need to add more of your own methods for sorting other class variables.
Now for the main class:
class Main {
public static void main(String[] args) {
//Get a mock array from the GetMockArray() function.
RecordReference[] refArray = GetMockArray();
//Instantiate an instance of BubbleSorter.
BubbleSorter sorter = new BubbleSorter();
//Invoke the SortByFirstName method contained within the BubbleSorter
//and store the sorted array in a variable of type RecordReference[] named
//sortedResult.
RecordReference[] sortedResult = sorter.SortByFirstName(refArray);
//Print out the results in the sorted array to check if they are in the correct
//order.
//This for loop is not required and is just so that we can see within the
//console what order the objects in the sortedResult are in.
for(int i = 0; i < sortedResult.length; i++)
{
System.out.println(sortedResult[i].getFirstName());
}
}
public static RecordReference[] GetMockArray()
{
//Instantiate a few RecordReferences with a different parameter for
//the firstName in each reference.
RecordReference ref1 = new RecordReference(0, "Ada", "Test", "Test", 22, "First",
"Computer Science", 1.0f);
RecordReference ref2 = new RecordReference(0, "Bob", "Test", "Test", 22, "First",
"Computer Science", 1.0f);
RecordReference ref3 = new RecordReference(0, "David", "Test", "Test", 22,
"First", "Computer Science", 1.0f);
//Create a variable of type RecordReference[] and add the RecordReferences
//Instantiated above in the wrong order alphabetically (Based on their firstName)
//class variables.
RecordReference[] refArray = {
ref2, ref3, ref1
};
return refArray;
}
}
In the main class I have provided verbose comments to explain exactly what is happening. One thing I would like to point out is that I have added a method named GetMockArray(). This is just in place to provide a RecordReference[] for testing and you probably want to do that somewhere else of your choosing.
If anything is not clear or you need some more assistance then just comment on this answer and I will try to help you further.
Thanks.

Removing item from ArrayList using remove(<index>) or remove(<objectRef>)

I want to create a program which displays current staff in the ArrayList before asking the user for input of a payroll number they'd like to remove. User then should input the payroll number of one of the three staff members and press enter. Upon pressing enter, the program should remove that particular staff member from the array list and display the entire list again (missing out the staff member they've deleted obviously). If the user no longer wishes to remove any payroll numbers, the payroll number entry should be 0 and should then display the contents of the list again.
The problem I'm having is with the remove part.
I've been recommended of two ways of achieving this:
This 'search' method should return either the position within the ArrayList (so that remove(<index>) may be used) or a reference to the object (so that remove(<objectRef>) may be used). If the staff member is not found, then the search method should return -1 (if remove(<index>) is being used) or null (if remove(<objectRef>) is being used).
However I am not sure how to implement this in Java.
Here is my file structure:
ArrayListTest.java
import java.util.*;
import personnelPackage.Personnel;
public class ArrayListTest
{
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args)
{
long searchQuery;
ArrayList<Personnel> staffList = new ArrayList<Personnel>();
Personnel[] staff =
{new Personnel(123456,"Smith","John"),
new Personnel(234567,"Jones","Sally Ann"),
new Personnel(999999,"Black","James Paul")};
for (Personnel person:staff)
staffList.add(person);
do
{
showDisplay(staffList);
System.out.print("\nPlease enter a payroll number to search: ");
searchQuery = keyboard.nextLong();
searchForPayrollNumber(staffList, searchQuery);
}while(!(searchQuery == 0));
}
private static void showDisplay(ArrayList<Personnel> staffList)
{
System.out.print("\n------------- CURRENT STAFF LIST -------------\n");
for (Personnel person : staffList)
{
System.out.println("Payroll number: " + person.getPayNum());
System.out.println("Surname: " + person.getSurname());
System.out.println("First name(s): " + person.getFirstNames() + "\n");
}
}
public static void searchForPayrollNumber(ArrayList<Personnel> staffList, long searchQuery)
{
long index = staffList.indexOf(searchQuery);;
for (Personnel person: staffList)
{
if (person.getPayNum() == searchQuery)
{
System.out.print("\n------------- Staff member found and removed! -------------");
System.out.println("\n\nFirst Name(s): " + person.getFirstNames());
System.out.println("\nSurname: " + person.getSurname());
System.out.print("\n-----------------------------------------------");
staffList.remove(index);
return;
}
}
System.out.print("\n------------- No staff members found. Program terminated -------------");
return;
}
}
Personnel.java (in its own package named personnelPackage)
package personnelPackage;
public class Personnel
{
private long payrollNum;
private String surname;
private String firstNames;
public Personnel(long payrollNum, String surname, String firstNames)
{
this.payrollNum = payrollNum;
this.surname = surname;
this.firstNames = firstNames;
}
public long getPayNum()
{
return payrollNum;
}
public String getSurname()
{
return surname;
}
public String getFirstNames()
{
return firstNames;
}
public void setSurname(String newName)
{
surname = newName;
}
}
Consider using Iterator for search and removal:
Iterator<Personnel> i = staffList.iterator();
while (i.hasNext()) {
Personnel p = i.next();
if (p.getPayNum() == searchQuery) {
// print message
i.remove();
return p;
}
}
return null;
If using List#remove() is strictly required, return found personnel p and call if (p != null) staffList.remove(p):
public static Personnel searchByPayNum(List<Personnel> ps, long num) {
for (Personnel p : ps) {
if (p.getPayNum() == num)
return p;
}
return null;
}
And in caller code:
Personnel p = searchByPayNum(staffList, query);
if (p != null) {
// log
staffList.remove(p);
}
public static long searchForPayrollNumber(ArrayList<Personnel> staffList, long searchQuery) {
//long index = staffList.indexOf(searchQuery);
for(int i = 0; i < staffList.size(); i++) {
if (staffList.get(i).getPayNum() == searchQuery) {
System.out.print("\n------------- Staff member found and removed! -------------");
System.out.println("\n\nFirst Name(s): " + staffList.get(i).getFirstNames());
System.out.println("\nSurname: " + staffList.get(i).getSurname());
System.out.print("\n-----------------------------------------------");
//staffList.remove(i);
return i;
}
}
System.out.print("\n------------- No staff members found. Program terminated -------------");
return -1;
}
Your search method shouldn't return void. It should return int or long instead,
public static long searchForPayrollNumber(ArrayList<Personnel> staffList, long searchQuery)
{
int index = -1;
for (int i = 0; i < staffList.size(); i++){
if(staffList.get(i).getPayNum() == searchQuery){
index = i;
System.out.print("\n------------- Found Staff member at position " + index + " in the list");
break;
}
}
if (index != -1){
staffList.remove(index);
System.out.print("\n------------- Removed the staff member");
}
return index;
}
Last approach returned the index. Now when you want to return the object:
public static long searchForPayrollNumber(ArrayList<Personnel> staffList, long searchQuery)
{
Personnel p = null;
for (int i = 0; i < staffList.size(); i++){
if(staffList.get(i).getPayNum() == searchQuery){
p = staffList.get(i);
break;
}
}
staffList.remove(p);
return p;
}
You must know that after removing it from the list, It will shift any subsequent elements to the left (subtracts one from their indices).
Also, just a suggestion:
Instead of
Personnel[] staff =
{new Personnel(123456,"Smith","John"),
new Personnel(234567,"Jones","Sally Ann"),
new Personnel(999999,"Black","James Paul")};
Why not
staffList.add(new Personnel(123456,"Smith","John"));
staffList.add(new Personnel(234567,"Jones","Sally Ann"));
staffList.add(new Personnel(999999,"Black","James Paul"));
This is just an advice. Since searching and removing are your primary goals, ArrayList is not the right collection to use.
Create a Hashmap with ID as key and Personnel object as value. This will help in identifying the Personnel in O(1) time and removal as well.
ArrayList should be used only when you know the index to read value. It then does that in O(1). If not, it is O(n) and not as efficient as HashMap.

Array lists to print customer objects

How would I use an array list of type Customer(Which has 2 child classes, nonmember and member) to print out all customer objects using a comparison? in other words, I want to check the array list at a certain index and check if it is a Non-member or member object and print output accordingly. here is my code:
ArrayList<Customer> customerList = new ArrayList<Customer>();
for(int i = 0; i < customerList.size(); i++)
{
if(customerList.get(i) == // nonmember)
{
// want to use toString in NonMemberCustomer class
}
else // member
{
// use toString in MemberCustomer class to print output.
}
}
public String toString()
{
return "\nMember Customer:" + super.toString() +
"Collected Points:\t" + pointsCollected + "\n\n";
}
public String toString()
{
return "NonMember Customer:" + super.toString() +
"Visit Fee:\t\t" + visitFee + "\n\n";
}
Declare your arraylist using Customer as the parametric type:
// So that the polymorphism would work
List<Customer> customerList = new ArrayList<>();
Second, you don't need an if/else statement to print the respective toString()s of your objects; just override the toString() method in each of your classes & polymorphism shall take it from there.
for(int i =0; i < customerList.size();i++) {
// Implicit call to the toString() method
System.out.println(customerList.get(i));
}
The classes: (e.g)
class Customer {
// properties & methods
#Override
public String toString() {
System.out.println("The customer's toString !");
}
}
class Member extends Customer {
// properties & methods
#Override
public String toString() {
System.out.println("The member's toString !");
}
}
class NonMember extends Customer {
// properties & methods
#Override
public String toString() {
System.out.println("The nonmember's toString !");
}
}

Need help searching a linked list [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
Hello everyone i have trouble searching a linked list. Basically I'm reading from a csv file and storing it in the linked list. I was able to add the list at the end. But when i search the list it keep saying it wasn't found. The method function is called contains. A method "contains" that takes a Country object as parameter and checks if the name of the country can be found in the list . to check whether object foo of type Country equals objects bar of type Country, you must override the "equals method" in class Country. When I'm running the code it returns not found and i found out the method contains from class countryNode returns null thats why its returns not found. I will appreciate the help thanks. Everything works except from the contains method. Below is my code:
public Country contains(Country obj)
{
if(this.isEmpty())
{
System.out.println("Sorry this is an Empty list");
return null;
}
else{
CountryNode current = first;
while(current!=null)
{
if(current.getCountry().equals(obj))
{
return current.getCountry();
// break;
}
current = current.getNext();
}
return null;
}
}
The class Country and the overrides method equals:
public class Country {
private String countryNames;
private SubscriptionYear[] subscriptions;
private int size;
private int location;
public Country(String country)
{
this.countryNames = country;
}
public Country(String country, int arraylength)
{
this.countryNames = country;
this.size = arraylength;
subscriptions = new SubscriptionYear[size];
location = 0;
}
public void addSubscriptionYear(int year, double subscription)
{
subscriptions[location]= new SubscriptionYear(year, subscription);
++location;
}
public String toString()
{
System.out.print(countryNames+"\t");
for(SubscriptionYear s: subscriptions)
{
//System.out.print(countryNames+"\t");
System.out.print(s.getSubscription()+"\t");
}
System.out.println();
return "";
}
public String getName()
{
return this.countryNames;
}
public boolean equals(Country obj)
{
return (this.countryNames==obj.countryNames);
}
}
This my test main file:
import java.util.Random;
import java.util.Scanner;
public class TestCountryList
{
/**
* Builds a list of countries to debug.
*/
private void debugListOfCountries(Country [] allCountries)
{
// TO COMPLETE
}
/**
* Builds a random list of countries.
*/
private void testRandomListOfCountries(Country [] allCountries)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("How many countries do you want to add to the list?");
int requestedSize = keyboard.nextInt();
// Build the list out of a random selection of countries.
Random random = new Random();
CountryList selectedCountries = new CountryList();
for (int i = 0; i < requestedSize; i++)
{
int selectedIndex = random.nextInt(allCountries.length);
selectedCountries.add(allCountries[selectedIndex]);
}
// Note: To debug your list, comment this line in
System.out.println("List of countries: " + selectedCountries);
// Check if the name of a country is in the list.
// If the country is found, print the details.
// Otherwise output not found.
System.out.println("\nWhat country do you want to search for?");
String countryToFind = keyboard.next();
Country obj = new Country(countryToFind);
Country foundCountry = selectedCountries.contains(obj);
if (foundCountry != null)
{
System.out.println("Country " + countryToFind + " found with details:" + foundCountry);
}
else
System.out.println("Country " + countryToFind + " not found.");
}
/**
* Includes test examples for class GraphView.
*/
public static void main(String[] args)
{
// Create and set objects of type Country
//
final String FILENAME = "data/cellular.csv"; // Directory path for Mac OS X
//final String FILENAME = "data\cellular.csv"; // Directory path for Windows OS (i.e. Operating System)
final int NUM_COUNTRIES_TO_TEST = 3; // Note: Include test cases in addition to 3
// Parse the CSV data file
//
CSVReader parser = new CSVReader(FILENAME);
String [] countryNames = parser.getCountryNames();
int [] yearLabels = parser.getYearLabels();
double [][] parsedTable = parser.getParsedTable();
// Create and set objects of type Country
//
Country [] countries;
countries = new Country[NUM_COUNTRIES_TO_TEST];
Country current;
countries = new Country[countryNames.length];
for (int countryIndex = 0; countryIndex < countries.length; countryIndex++)
{
int numberOfYears = yearLabels.length; // OR numberOfYears = dataTable[countryIndex].length;
current = new Country(countryNames[countryIndex], numberOfYears);
for (int yearIndex = 0; yearIndex < numberOfYears; yearIndex++)
{
double [] allSubscriptions = parsedTable[countryIndex];
double countryData = allSubscriptions[yearIndex];
current.addSubscriptionYear(yearLabels[yearIndex], countryData);
}
countries[countryIndex] = current;
}
TestCountryList application = new TestCountryList();
// Note: Initially, to test your output you may hard code the number of
// countries added, and the array positions selected.
// However, make sure to comment this out before submitting your work.
//application.debugListOfCountries(countries);
application.testRandomListOfCountries(countries);
}
}
Try overriding equals method of Object as below:
public boolean equals(Object obj)
{
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
return (this.countryNames.equals(((Country)obj).countryNames));
}
internally contains call countryList.equals method and equals method's signature is
public boolean equals(Object obj) {}
As opposed to
public boolean equals(Country obj) {}
Also you are just comparing two reference of strings while you need to compare the contents of String. So instead of
this.countryNames==obj.countryNames
You should say:
this.countryNames.equals(obj.countryNames);
you need to use equals or equalsIgnoreCase to compare String
public boolean equals(Country obj)
{
return this.countryNames.equals(obj.countryNames);
}

Categories

Resources