Remove element from ArrayList using user input and iterator - java

I need to remove an element from an ArrayList, based on the user input. So what I have is an ArrayList where a user can register dogs. Then if the user wants to remove a dog, he/she should be able to do it by using the command "remove dog" followed by the name of the dog.
I have tried using an iterator, but when using it only the else statement is used and "Nothing has happened" is printed out on the screen.
import java.util.Iterator;
import java.util.Scanner;
import java.util.ArrayList;
public class DogRegister {
ArrayList<Dog> dogs = new ArrayList<>();
private Scanner keyboard = new Scanner(System.in);
public static void initialize() {
System.out.println("Welcome to this dog application");
}
private boolean handleCommand(String command) {
switch (command) {
case "One":
return true;
case "register new dog":
registerNewDog();
break;
case "increase age":
increaseAge();
break;
case "list dogs":
listDogs();
break;
case "remove dog":
removeDog();
break;
default:
System.out.println("Error: Unknown command");
}
return false;
}
private void registerNewDog() {
System.out.print("What is the dog's name? ");
String dogNameQuestion = keyboard.nextLine().toLowerCase().trim();
System.out.print("Which breed does it belong to? ");
String dogBreedQuestion = keyboard.nextLine().toLowerCase().trim();
System.out.print("How old is the dog? ");
int dogAgeQuestion = keyboard.nextInt();
System.out.print("What is its weight? ");
int dogWeightQuestion = keyboard.nextInt();
keyboard.nextLine();
Dog d = new Dog(dogNameQuestion, dogBreedQuestion, dogAgeQuestion,
dogWeightQuestion);
dogs.add(d);
System.out.println(dogs.get(0).toString());
}
private void removeDog() {
System.out.print("Enter the name of the dog ");
String removeDogList = keyboard.nextLine();
for (Iterator<Dog> dogsIterator = dogs.iterator();
dogsIterator.hasNext();) {
if (removeDogList.equals(dogsIterator)) {
System.out.println("The dog has been removed ");
break;
} else {
System.out.println("Nothing has happened ");
break;
}
}
}
public void closeDown() {
System.out.println("Goodbye!");
}
public void run() {
initialize();
runCommandLoop();
}
public static void main(String[] args) {
new DogRegister().run();
}
}

You compare a String will an Iterator as said by JB Nizet :
if (removeDogList.equals(dogsIterator)) {
It will never return true.
Besides even invoking next() on the iterator will not solve the problem as a String cannot be equal to a Dog object either.
Instead of, compare String with String when you use equals() and invoke Iterator.remove() to effectively remove the current iterated element.
That should be fine :
private void removeDog() {
System.out.print("Enter the name of the dog ");
String removeDogList = keyboard.nextLine();
for (Iterator<Dog> dogsIterator = dogs.iterator();dogsIterator.hasNext();) {
Dog dog = dogsIterator.next();
if (removeDogList.equals(dog.getName())) {
dogsIterator.remove();
System.out.println("The dog has been removed");
return;
}
}
System.out.println("Nothing has been removed");
}

An Iterator<Dog> can't possibly be equal to a String: they don't even have the same type.
Only a String can be equal to a String.
You want to get the next value of the iterator, which is a Dog. Then you want to compare the name of the dog with the String input.
And then you want to remove the dog, using the iterator's remove() method. Read the javadoc of Iterator.

Related

Give one array to mutltiple methods [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
For example, we have 5 courses available: comp2011, comp2012, comp2013, comp2014, comp2015.
When adding or dropping a course, you need to specify the student's name (you may assume it is unique) and the course that is going to be added/dropped.
For adding a course, if the student has already enrolled in at least one course, the system will append the newly added course to his/her course record. But if it is the first time the student is trying to add courses, the system will create a record for him/her and state that this is the first course of this student (see sample output below)...
The system should support listing the courses that the student has enrolled in.
The system should support some basic validation check: Students cannot add the same course two times nor drop a course that is not enrolled.
When dropping the last course, there will be nothing in the student course list, but the system should still keep the empty file for him/her so that when another course is added, it knows that this is not the first time.
How Can I Make the Array that is going to support all my methods at once knowing that I made a method for adding, dropping, listing and quitting.(Quiting is not having an array)
This is where I am at now:
import java.util.*;
public class codeTraining {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String AddDrop = "";
while (!AddDrop.equals("Q")) {
System.out.println("Add-Drop Course Menu");
System.out.println("A for Add, D for Drop, L for List, Q for Quit");
AddDrop = input.nextLine();
switch (AddDrop) {
case "A" -> A();
case "D" -> D();
case "L" -> L();
case "Q" -> Q();
default -> System.out.println("Please enter a valid Character!");
}
}
}
public static void A() {
Scanner input = new Scanner(System.in);
String name;
String course;
System.out.println("Please enter the student name:");
name = input.nextLine();
System.out.println("Please enter the course you want to add:");
course = input.nextLine();
System.out.println("Adding course : " + course);
System.out.println("Add course successfully");
}
public static void D() {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a student name");
String name = input.nextLine();
System.out.println("please enter the course you want to drop:");
String course = input.nextLine();
System.out.println("Dropping course: " + course);
System.out.println("Drop course successfully");
}
public static void L() {
Scanner input = new Scanner(System.in);
String name, course;
System.out.println("Please enter the student name");
name = input.nextLine();
}
public static void Q() {
System.out.println("Quit...");
}
}
You could use a hashmap for this problem, as it will allow you to quickly and easily look up the courses of students. It's declared as a global variable outside all of the methods, which means it can be accessed by any of them.
import java.util.*;
public class codeTraining {
//Hashmap contains names that are mapped to lists of courses
static HashMap<String, ArrayList<String>> map =
new HashMap<String, ArrayList<String>>();
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String AddDrop = "";
while (!AddDrop.equals("Q")) {
System.out.println("Add-Drop Course Menu");
System.out.println("A for Add, D for Drop, L for List, Q for Quit");
AddDrop = input.nextLine();
//added breaks to the switch statement
switch (AddDrop) {
case "A": A(); break;
case "D": D(); break;
case "L": L(); break;
case "Q": Q(); break;
default: System.out.println("Please enter a valid Character!");
}
}
}
public static void A() {
Scanner input = new Scanner(System.in);
String name;
String course;
System.out.println("Please enter the student name:");
name = input.nextLine();
System.out.println("Please enter the course you want to add:");
course = input.nextLine();
System.out.println("Adding course : " + course);
//if the map contains the name already
if (map.containsKey(name)) {
//if the student already had the course in its list
if (map.get(name).contains(course)) {
System.out.println("The student is already taking this course");
return;
} else {
//adding the course to the list that's mapped
//to the student's name in the hashmap
map.get(name).add(course);
}
}
//if student isn't in the system
else {
//create a new arraylist with the new course in it
ArrayList<String> courses = new ArrayList<String>();
courses.add(course);
//add a map between the student's name and his course list
map.put(name, courses);
}
System.out.println("Add course successfully");
}
public static void D() {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a student name");
String name = input.nextLine();
System.out.println("please enter the course you want to drop:");
String course = input.nextLine();
System.out.println("Dropping course: " + course);
//checks if name in system
if (map.containsKey(name)) {
if (map.get(name).contains(course)) {
//removing if list had the course in it
map.get(name).remove(course);
} else {
System.out.println("This student isn't taking that course");
return;
}
} else {
System.out.println("This student isn't in the system");
return;
}
System.out.println("Drop course successfully");
}
public static void L() {
Scanner input = new Scanner(System.in);
String name, course;
System.out.println("Please enter the student name");
name = input.nextLine();
if (map.containsKey(name)) {
//printing out courses for specified student
ArrayList<String> courses = map.get(name);
for (int i = 0; i < courses.size(); i++) {
System.out.print(courses.get(i) + " ");
}
} else {
System.out.println("This student isn't in the system");
}
}
public static void Q() {
System.out.println("Quit...");
}
}
I added some comments in case you were new to hashmaps. Basically, map.put(key, value) will add a mapped pair to the list so that when you call map.get(key), it will return whatever value you put it to. I hope this helps, and feel free to ask if you're confused.

How do I create a class designated to store an array, and then call it from any other method?

I am trying to clean my code up by creating a class specifically for an array of information. It is basically like a storage for variables in case I need them later. Here is what I have so far:
package com.input;
import java.util.Scanner;
public class Gender extends Welcome {
Scanner input = new Scanner(System.in);
private static String gender;
public static void setGender() {
Scanner input = new Scanner(System.in);
int[] storeInts = new int[25];
storeInts[0] = 0;
//The [0] index of array storeInformation is the gender value. 0 = female; 1 = male
gender = input.nextLine();
if(gender.equalsIgnoreCase("boy")) {
System.out.println("What is your name, sir?");
while (storeInts[0] < 1) {
storeInts[0]++;
}
}else if(gender.equalsIgnoreCase("girl")) {
System.out.println("What is your name, ma'am?");
}else{
System.out.println("You have failed to answer correctly. Try again:");
init();
}
Name nameObject = new Name();
nameObject.setName(storeInts[0]);
}
public static void nextName(int x) {
if(x == 1) {
System.out.println("What is your name, sir?");
}else{
System.out.println("What is your name, ma'am?");
}
Name nameObject = new Name();
nameObject.setName2();
}
}
What I'm trying to accomplish here, is if the user types "boy" my code will store 1 in the index [0] of array storeInts[]. If the user types "girl" the index [0] will remain the value of 0.
If I need to refer to the user's gender later on, I want to be able to go back and figure out if they are a "boy" or a "girl" using the array.
I want to be able to called this array from any method within my code. I have already used this array in a complicated way and I would like to find a solution to make it easier.
Here is when I used it:
nameObject.setName(storeInts[0]);
I transferred the index [0] to the setName() method.
Here is the setName() method:
public void setName(int x) {
String name;
name = input.nextLine();
String storedStrings[] = new String[25];
storedStrings[0] = name;
FirstTask firstTaskObject = new FirstTask();
if (name.length() == 0) {
System.out.println("You must be a unicorn. You want to play games?");
altInit(x);
}else{
System.out.println("Nice to meet you, " + name + "!");
firstTaskObject.beginning(name);
}
}
As you can see I created another array in the same manner as the previous one, but this one is to store Strings instead. Now back to what I was saying-- the parameter (int x) is the same value as storeInts[0]. This will tell me if the user is male or female. This value is sent to altInit() method when the user decides to try to continue without typing their name in first.
Here is the altInit() method:
public void altInit(int x) {
String yesOrNo;
AltStory altStoryObject = new AltStory();
Gender backToGender = new Gender();
yesOrNo = input.nextLine();
if(yesOrNo.equalsIgnoreCase("yes")) {
altStoryObject.AltInit();
}else if(yesOrNo.equalsIgnoreCase("no")) {
System.out.println("Consider this your last warning...");
backToGender.nextName(x);
}else{
System.out.println("You have failed to answer correctly. Try again:");
init();
}
}
When asked if they want to play games, they can type "yes" or "no." If the user types "no" as in they do not want to play games, then the program will print, "Consider this your last warning..." and then continue to the nextName() method in the previous class Gender. This also passes on that index[0] again in the array storedInts[].
Here is the nextName() method:
public static void nextName(int x) {
if(x == 1) {
System.out.println("What is your name, sir?");
}else{
System.out.println("What is your name, ma'am?");
}
Name nameObject = new Name();
nameObject.setName2();
}
As you can see, if the user is that value of a male (or 1) then the program will print, "What is your name, sir?." If the value is a female (or 0), then the program will print, "What is your name, ma'am?"
This whole time I felt like the stored value of storeInts[0], was just leap frogging around until it was used... I want to prevent this by just creating a class with methods giving me the ability to call any value stored in that array whenever I need it. How do I create an array, store it in a method, and call it when needed?
As someone has requested, here is the entire code:
//Gender class
package com.input;
import java.util.Scanner;
public class Gender extends Welcome {
Scanner input = new Scanner(System.in);
private static String gender;
public void setGender() {
Scanner input = new Scanner(System.in);
int [] storeInts = new int[25];
storeInts[0] = 0;
//The [0] index of array storeInformation is the gender value. 0 = female; 1 = male
gender = input.nextLine();
if (gender.equalsIgnoreCase("boy")) {
System.out.println("What is your name, sir?");
while(storeInts[0]<1){
storeInts[0]++;
}
} else if (gender.equalsIgnoreCase("girl")) {
System.out.println("What is your name, ma'am?");
} else {
System.out.println("You have failed to answer correctly. Try again:");
init();
}
Name nameObject = new Name();
nameObject.setName(storeInts[0]);
}
public void nextName(int x){
if (x == 1) {
System.out.println("What is your name, sir?");
}else {
System.out.println("What is your name, ma'am?");
}
Name nameObject = new Name();
nameObject.setName2();
}
}
//Name class
package com.input;
public class Name extends Gender{
public void setName(int x) {
String name;
name = input.nextLine();
String storedStrings[] = new String[25];
storedStrings[0] = name;
FirstTask firstTaskObject = new FirstTask();
if (name.length() == 0) {
System.out.println("You must be a unicorn. You want to play games?");
altInit(x);
} else {
System.out.println("Nice to meet you, " + name + "!");
firstTaskObject.beginning(name);
}
}
public void altInit(int x){
String yesOrNo;
AltStory altStoryObject = new AltStory();
Gender backToGender = new Gender();
yesOrNo = input.nextLine();
if(yesOrNo.equalsIgnoreCase("yes")) {
altStoryObject.AltInit();
}else if(yesOrNo.equalsIgnoreCase("no")){
System.out.println("Consider this your last warning...");
backToGender.nextName(x);
}else{
System.out.println("You have failed to answer correctly. Try again:");
init();
}
}
public void setName2() {
String name;
name = input.nextLine();
FirstTask firstTaskObject = new FirstTask();
if (name.length() == 0) {
System.out.println("You have failed to answer correctly. Try again:");
init();
} else {
System.out.println("Nice to meet you, " + name + "!");
firstTaskObject.beginning(name);
}
}
}
How do I create an array, store it in a method, and call it when needed?

Loop ending abruptly and Java not saving object?

So I'm having a problem with my code where my loop is ending for after my "C" case. I need it to print out a message saying the store is full and keep loop back up and print out the main menu. Also, my Pet3 is not being saved when I list all the pets after adding a new one. My
import java.util.*;
public class MainPets
{
static Scanner scan = new Scanner(System.in);
private static String Userinput;
private static void mainmenu(){
System.out.println("A."+" " + "List the pets in the store.");
System.out.println("B."+" " + "Age up the pets");
System.out.println("C."+" " + "Add a new pet");
System.out.println("D."+" " + "Adopt a pet");
System.out.println("E."+" " + "Quit");
Userinput=scan.nextLine();
}
public static String Getuserinput(){
return Userinput;
}
public static void main (String [] args){
int Pet3age;
String Pet3name;
Pet Pet1=new Pet("Fido",3);
Pet Pet2=new Pet("furball",1);
int Userinputint;
Pet Pet3=null;
System.out.println("Welcome to the pet store.Type the letter to make your selection");
MainPets.mainmenu();
while(Userinput.equals("A")||Userinput.equals("B")||Userinput.equals("C")||Userinput.equals("D")||Userinput.equals("E")){
switch(Userinput) {
case "A":
System.out.println("Fido is "+Pet1.GetAge()+ " years old and is " + Pet1.Getadoptionstatus());
System.out.println("furball is " + Pet2.GetAge()+ " years old and is " + Pet2.Getadoptionstatus());
Userinput=scan.nextLine();
case "B":
System.out.println("Everyone just got a little older.");
Pet1.ageincrease();
Pet2.ageincrease();
Userinput=scan.nextLine();
case "C":
if (Pet3!=null){
System.out.println("Sorry the store is full");
Userinput=scan.nextLine();
}/* If the Pet 3 spot has been filled I want it to print this
and loop back up to print the main menu again.*/
if(Pet3==null){
System.out.println("Please type in a name");
Pet3name=scan.nextLine();
System.out.println("Please type in an age");
Pet3age=scan.nextInt();
Pet3=new Pet(Pet3name,Pet3age);/*This line is Not saving Pet3 as
a "Pet" class and when I try to list all the pets by pressing
A when it loops back up , Pet3 does not show up as a Pet*/
Userinput=scan.nextLine();/* This is where my program just
ends.It doesn't even take a user input */
}
case "D":
//will add later on
break;
case "E":
//will add later on
break;
}
}
Here is the code for my Pet class:
public class Pet {
String Name, AdoptionStatus, True = "not adopted";
int Age;
public Pet() {}
public Pet(String Name, int Age) {
this.Name = Name;
this.Age = Age;
}
public void SetName(String namesetup) {
Name = namesetup;
}
public String GetName() {
return Name;
}
public int GetAge() {
return Age;
}
public int ageincrease() {
return Age++;
}
public String Getadoptionstatus() {
return AdoptionStatus;
}
public void Setadoptionstatus(String setadoption2) {
AdoptionStatus = True;
}
}
Your loop is extting when Pet3!=null because you are not taking any input from the scanner after it.
Take input in both conditions inside case "C":
if (Pet3!=null){
System.out.println("Sorry the store is full");
} else {
System.out.println("Please type in a name");
Pet3name=scan.nextLine();
System.out.println("Please type in an age");
Pet3age=scan.nextInt();
Pet3=new Pet(Pet3name,Pet3age);/*This line is Not saving Pet3 as
a "Pet" class and when I try to list all the pets by pressing
A when it loops back up , Pet3 does not show up as a Pet*/
}
Userinput=scan.nextLine(); //make sure to keep this line outside the curly braces.
break;

editing in arraylist with multiple strings

I have made a program...
in which I scan 3 different strings and then convert them into a single string using toString() then I put that string into array list
for example
"name phonenumber addrees"
it works fine....the problem is when i have to edit it...
i use string.split to split them and edit them...
but i dont know what is wrong..whenever i try to edit it goes to exception error...can anyone help me out?
PROBLEM IN CASE 3 of first switch
import java.util.ArrayList;
import java.util.Scanner;
public class mainClass {
public static void main(String[] args) {
Scanner input= new Scanner(System.in);
ArrayList<String> arraylist= new ArrayList<String>();
CreateFormat FormatObject = new CreateFormat();
int choice;
String phoneNumber;
String name,address;
String format="Empty";
int x=1;
int flag=0;
do
{
try
{
System.out.println("Enter your choice");
System.out.printf("1:Enter new data\n2:Display data");
choice=Integer.parseInt(input.next());
switch (choice)
{
case 1:
{
System.out.println("Enter name ");
name=input.next();
System.out.println("Enter phone number");
phoneNumber=input.next();
System.out.println("Enter address");
address=input.next();
format=FormatObject.toString(phoneNumber, name, address); // will merge these 3 Strings with space in between
arraylist.add(format);
flag++;
}
break;
case 2:
{
System.out.println("Name Phone number Address");
System.out.println();
for(int i=0;i<flag;i++)
{
System.out.println(arraylist.get(i)); //arraylist cant be displayed on nextline without loop
}
}
break;
case 3:
{
System.out.println("Enter the position you want to edit");
System.out.println("1:Name\n2:Phone number\n3:Address");
int choice2;
choice2=input.nextInt();
String dupFormat= arraylist.get(choice2-1);
String[] splitString= dupFormat.split(" ");
switch (choice2)
{
case 1:
{ System.out.println("Enter new name");
splitString[0]=input.next();
break;
}
case 2:
{ System.out.println("Enter new phone number");
splitString[1]=input.next();
}
break;
case 3:
{ System.out.println("Enter new Address");
splitString[2]=input.next();
}
break;
default:
{
System.out.println("Choice is only 1,2,3 ");
}
String newFormat=splitString.toString();
arraylist.add(choice2-1, newFormat);
}
}break;
default:
System.out.println("Error");
break;
}
}
catch(Exception InputMismatchException){
System.out.println("Enter right choice ..");
}
}while(x==1);
}}
my toString method--->
public class CreateFormat {
String phoneNumber;
String nameUser;
String addressUser;
public String toString(){
return String.format("%s %s %s", nameUser,phoneNumber,addressUser);
}
public String toString (String phone,String name,String address){
phoneNumber=phone;
nameUser=name;
addressUser=address;
return String.format("%s %s %s", nameUser,phoneNumber,addressUser);
}
}
You have break; statement outside of your second switch cases. For example you have break; outside of
case 2:
{ System.out.println("Enter new phone number");
splitString[1]=input.next();
}
break;
And it will break first switch.
So new string won't add into array. And even if you call this
String newFormat=splitString.toString();
arraylist.add(choice2-1, newFormat);
it will change your data to somthing like [Ljava.lang.String;#1f7030a6. It's because you trying to call toString() on newly created array from dupFormat.split(" ").
I'd recomended change case 3 section to
System.out.println("Enter the position you want to edit");
System.out.println("1:Name\n2:Phone number\n3:Address");
int choice2;
choice2 = input.nextInt();
String dupFormat = arraylist.get(choice2 - 1);
String[] splitString = dupFormat.split(" ");
switch (choice2) {
case 1: {
System.out.println("Enter new name");
FormatObject.nameUser = input.next();
break;
}
case 2: {
System.out.println("Enter new phone number");
FormatObject.phoneNumber = input.next();
break;
}
case 3: {
System.out.println("Enter new Address");
FormatObject.addressUser = input.next();
break;
}
default: {
System.out.println("Choice is only 1,2,3 ");
}
}
String newFormat = FormatObject.toString();
arraylist.add(choice2 - 1, newFormat);
break;
And you will change state of your object and after that you can call toString() again with new data.
couldn't find the issue but your code is very hard to read..
Why would you want to store the Name, Phone number and Address as a String?
I would suggest:
creating a class that contains those fields.
create a function that will implement the code you have in each case (that way you can also test each function seperatly)
in the functions work with an instance of the class from (1) and convert to string only when you want to print.
I would also get read of the do-while, switch but that is up to you
also try to give more meaningful names when you code.. your flag for example is used as a count and not a flag.
so you should do something like this: (and test every function individually)
private List<PersonalData> list = new ArrayList<>();
///....
switch(choise){
case 1://consider replacing with enum
{
list.add(getPersonalDataFromInput());
break;
}
case 2:
{
printAll();
break;
}
case 3:
{
System.out.println("Enter the position you want to edit");
System.out.println("1:Name\n2:Phone number\n3:Address");
int choice2;
choice2=input.nextInt();
String dupFormat= arraylist.get(choice2-1);
if(choice2==1){
list.get(list.size()-1).setName(input.next());
}
else if(choice2==2){
list.get(list.size()-1).setPhone(input.next());
}
else (choice2==3){
list.get(list.size()-1).setAddress(input.next());
}
}
}
}
and the class to create:
class PersonalData{
private String phoneNumber;
private String name;
private String address;
//getters and setters
}
The problem in this code was the choice object..
Because if the input is a wrong input,choice object stays like that forever
that's there should be two objects for the input

Arraylist indexOf always returns -1 Java

I'm doing a project for class in which you have to make a Hall of Fame and be able to add/remove/search/edit different kinds of bands. Right now, I'm having trouble with searching the index for a specific band because it always returns -1 and I'm not sure why.
Here is my code:
public class HallofFame
{
public static ArrayList<Band> hallOfFame = new ArrayList<Band>();
public static Scanner scan = new Scanner(System.in);
public static void main(String[]args){
int a = 0;
while(a == 0){
System.out.println("What would you like to do?");
System.out.println("");
System.out.println("1. Add");
System.out.println("2. Remove");
System.out.println("3. Edit");
System.out.println("4. Clear");
System.out.println("5. Search");
System.out.println("6. Quit");
System.out.println("");
String choice = scan.nextLine();
if(choice.equals ("1")){
add();
}
else if(choice.equals ("2")){
remove();
}
else if(choice.equals ("3")){
edit();
}
else if(choice.equals ("4")){
clear();
}
else if(choice.equals ("5")){
search();
}
else if(choice.equals ("6")){
quit();
break;
}
}
}
public static void add(){
Scanner booblean = new Scanner(System.in);
System.out.println("What is the name of the band you would like to add?");
String name = scan.nextLine();
System.out.println("What kind of genre is this band?");
String genre = scan.nextLine();
System.out.println("How many members are in the band?");
int numMem = scan.nextInt();
System.out.println("How many songs does this band have?");
int numSongs = scan.nextInt();
System.out.println("How many albums does this band have?");
int numAlbs = scan.nextInt();
System.out.println("Is this band currently active?");
String yesno = booblean.nextLine();
boolean isActive = false;
if(yesno.equalsIgnoreCase ("yes")){
isActive = true;
}
Band b1 = new Band(name, genre, numMem, numSongs, numAlbs, isActive);
hallOfFame.add(b1);
System.out.println("");
System.out.println("The band " + name + " has been added to the database.");
System.out.println("");
}
public static void remove(){
}
public static void edit(){
System.out.println("What band info do you want to edit?");
String searchband = scan.nextLine();
}
public static void clear(){
hallOfFame.clear();
}
public static void search(){
System.out.println("What band name are you searching for?");
String searchband = scan.nextLine();
int retval = hallOfFame.indexOf(searchband);
System.out.println("The band " + searchband + " is at index: " + retval);
}
public static void quit(){
System.exit(0);
}
}
The search method is the one I'm having trouble with.
The problem is that hallOfFame contains Band objects, but you're searching hallOfFame for a String. Instead, iterate through hallOfFame and compare band names to the inputted string.
Alternatively, you can override the equals method of Band so that indexOf would actually work.
I'd imagine it would read something like this:
#Override
public boolean equals(Object o) {
return ((Band) o).name==this.name;
}
You should override both equals and hashCode to make it work perfectly.
Overriding equals and hashCode in Java
One way is you need make a Band's constructor with param is name. Then you can search the Object "Band" in ArrayList hallOfFame

Categories