#java #arrays #arraylist #add
Вопрос:
Здравствуйте, у меня возникла проблема с тем, как найти в моем списке массивов животное с ложным резервом, и если оно найдено, как напечатать имя этого животного. Мне нужно сделать это для всех животных в обоих списках массивов. Я прикрепил свой код ниже. Я не могу найти правильный метод для поиска по списку массивов, а затем печати имени этого объекта, если элемент найден.
import java.util.ArrayList;
import java.util.Scanner;
public class Driver {
private static ArrayList<Dog> dogList = new ArrayList<Dog>();
private static ArrayList<Monkey> monkeyList = new ArrayList<Monkey>();
// Instance variables (if needed)
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
initializeDogList();
initializeMonkeyList();
//Menu loop
while(true) {
displayMenu();
String menuOption = scnr.nextLine();
if (menuOption.equals("1")) {
intakeNewDog(scnr);
}
else if (menuOption.equals("2") ) {
intakeNewMonkey(scnr);
}
else if (menuOption.equals("3")) {
reserveAnimal(scnr);
}
else if (menuOption.equals("4")) {
printAnimals("dog");
}
else if (menuOption.equals("5")) {
printAnimals("monkey");
}
else if (menuOption.equals("6")){
printAnimals("available");
}
else if (menuOption.equals("q")) {
break;
}
else {
System.out.print("Invalid Input");
}
}
}
// This method prints the menu options
public static void displayMenu() {
System.out.println("nn");
System.out.println("ttttRescue Animal System Menu");
System.out.println("[1] Intake a new dog");
System.out.println("[2] Intake a new monkey");
System.out.println("[3] Reserve an animal");
System.out.println("[4] Print a list of all dogs");
System.out.println("[5] Print a list of all monkeys");
System.out.println("[6] Print a list of all animals that are not reserved");
System.out.println("[q] Quit application");
System.out.println();
System.out.println("Enter a menu selection");
}
// Adds dogs to a list for testing
public static void initializeDogList() {
Dog dog1 = new Dog("Spot", "German Shepherd", "male", "1", "25.6", "05-12-2019", "United States", "intake", false, "United States");
Dog dog2 = new Dog("Rex", "Great Dane", "male", "3", "35.2", "02-03-2020", "United States", "Phase I", false, "United States");
Dog dog3 = new Dog("Bella", "Chihuahua", "female", "4", "25.6", "12-12-2019", "Canada", "in service", true, "Canada");
dogList.add(dog1);
dogList.add(dog2);
dogList.add(dog3);
}
// Adds monkeys to a list for testing
public static void initializeMonkeyList() {
}
//Intakes a new dog
public static void intakeNewDog(Scanner scanner) {
System.out.println("What is the dog's name?");
String name = scanner.nextLine();
for(Dog dog: dogList) {
if(dog.getName().equalsIgnoreCase(name)) {
System.out.println("nnThis dog is already in our systemnn");
return; //returns to menu
}
}
//Gathers all information for new dog
System.out.println("What is the dog's breed?");
String breed = scanner.nextLine();
System.out.println("What is the dog's gender?");
String gender = scanner.nextLine();
System.out.println("What is the dog's age?");
String age = scanner.nextLine();
System.out.println("What is the dog's weight");
String weight = scanner.nextLine();
System.out.println("In what country was the dog acquired?");
String acquisitionDate = scanner.nextLine();
System.out.println("Where was the dog acquired?");
String acquisitionCountry = scanner.nextLine();
System.out.println("What is the dog's training status?");
String trainingStatus = scanner.nextLine();
System.out.println("What country is the dog in service?");
String inServiceCountry = scanner.nextLine();
//Creates a new object for dogList
Dog objt = new Dog(name, breed, gender, age, weight, acquisitionDate,
acquisitionCountry, trainingStatus, false, inServiceCountry);
//adds new dog to dogList
dogList.add(objt);
//End message to let user know that the animal has been added.
System.out.println("Thank you! " name " has been added to the system.");
}
// For the project submission you must also validate the input
// to make sure the monkey doesn't already exist and the species type is allowed
public static void intakeNewMonkey(Scanner scanner) {
System.out.println("What is the monkey's name?");
String name = scanner.nextLine();
for(Monkey monkey: monkeyList) {
if(monkey.getName().equalsIgnoreCase(name)) {
System.out.println("nnThis monkey is already in our systemnn");
return;
}
}
System.out.println("What is the monkey's gender?");
String gender = scanner.nextLine();
System.out.println("What is the monkey's age?");
String age = scanner.nextLine();
System.out.println("What is the monkey's weight?");
String weight = scanner.nextLine();
System.out.println("When was the monkey acquired?");
String acquisitionDate = scanner.nextLine();
System.out.println("What country was the monkey acquired in?");
String acquisitionCountry = scanner.nextLine();
System.out.println("What is the monkey's training status?");
String trainingStatus = scanner.nextLine();
System.out.println("What country is the monkey in service?");
String inServiceCountry = scanner.nextLine();
System.out.println("What is the monkey's tail length?");
String tailLength = scanner.nextLine();
System.out.println("What is the monkey's height?");
String height = scanner.nextLine();
System.out.println("What is the monkey's body length?");
String bodyLength = scanner.nextLine();
System.out.println("What is the monkey's species?");
String species = scanner.nextLine();
Monkey objt = new Monkey(name, gender, age, weight, acquisitionDate,
acquisitionCountry, trainingStatus, false,
inServiceCountry, tailLength, height,
bodyLength, species);
monkeyList.add(objt);
System.out.println("Thank you! " name " has been added to the system.");
}
// Complete reserveAnimal
// You will need to find the animal by animal type and in service country
public static void reserveAnimal(Scanner scanner) {
System.out.println("What type of animal would you like to reserve?");
String animalType = scanner.nextLine();
if (animalType == "dog") {
}
else if (animalType == "monkey") {
}
else {
System.out.println("Invalid animal.");
}
System.out.println("What country is the animal in service?");
String inServiceCountry = scanner.nextLine();
}
// Complete printAnimals
// Include the animal name, status, acquisition country and if the animal is reserved.
// Remember that this method connects to three different menu items.
// The printAnimals() method has three different outputs
// based on the listType parameter
// dog - prints the list of dogs
// monkey - prints the list of monkeys
// available - prints a combined list of all animals that are
// fully trained ("in service") but not reserved
// Remember that you only have to fully implement ONE of these lists.
// The other lists can have a print statement saying "This option needs to be implemented".
// To score "exemplary" you must correctly implement the "available" list.
public static void printAnimals(String type) {
String listType = type;
if (listType == "dog") {
System.out.println(dogList.toString());
}
else if(listType == "monkey") {
System.out.println(monkeyList.toString());
}
else {
}
}
}
public class Dog extends RescueAnimal {
// Instance variable
private String breed;
// Constructor
public Dog(String name, String breed, String gender, String age,
String weight, String acquisitionDate, String acquisitionCountry,
String trainingStatus, boolean reserved, String inServiceCountry) {
setName(name);
setBreed(breed);
setGender(gender);
setAge(age);
setWeight(weight);
setAcquisitionDate(acquisitionDate);
setAcquisitionLocation(acquisitionCountry);
setTrainingStatus(trainingStatus);
setReserved(reserved);
setInServiceCountry(inServiceCountry);
}
// Accessor Method
public String getBreed() {
return breed;
}
// Mutator Method
public void setBreed(String dogBreed) {
breed = dogBreed;
}
@Override
public String toString() {
return getName();
}
}
public class Monkey extends RescueAnimal {
//Monkey Variables
private String tailLength;
private String height;
private String bodyLength;
private String species;
//Constructor
public Monkey(String name, String gender, String age, String weight,
String acquisitionDate, String acquisitionCountry, String trainingStatus,
boolean reserved, String inServiceCountry,String tailLength, String height,
String bodyLength, String species) {
setTailLength(tailLength);
setHeight(height);
setBodyLength(bodyLength);
setSpecies(species);
setName(name);
setGender(gender);
setAge(age);
setWeight(weight);
setAcquisitionDate(acquisitionDate);
setAcquisitionLocation(acquisitionCountry);
setTrainingStatus(trainingStatus);
setReserved(reserved);
setInServiceCountry(inServiceCountry);
}
//Mutator
public void setTailLength(String TailLength){
tailLength = TailLength;
}
public void setHeight(String Height) {
height = Height;
}
public void setBodyLength(String BodyLength) {
bodyLength = BodyLength;
}
public void setSpecies(String Species) {
species = Species;
}
//Accessor
public String getTailLength() {
return tailLength;
}
public String getHeight() {
return height;
}
public String getBodyLength() {
return bodyLength;
}
public String getSpecies() {
return species;
}
@Override
public String toString() {
return getName();
}
}
import java.lang.String;
public class RescueAnimal {
// Instance variables
private String name;
private String animalType;
private String gender;
private String age;
private String weight;
private String acquisitionDate;
private String acquisitionCountry;
private String trainingStatus;
private boolean reserved;
private String inServiceCountry;
// Constructor
public RescueAnimal() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAnimalType() {
return animalType;
}
public void setAnimalType(String animalType) {
this.animalType = animalType;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
public String getAcquisitionDate() {
return acquisitionDate;
}
public void setAcquisitionDate(String acquisitionDate) {
this.acquisitionDate = acquisitionDate;
}
public String getAcquisitionLocation() {
return acquisitionCountry;
}
public void setAcquisitionLocation(String acquisitionCountry) {
this.acquisitionCountry = acquisitionCountry;
}
public boolean getReserved() {
return reserved;
}
public void setReserved(boolean reserved) {
this.reserved = reserved;
}
public String getInServiceLocation() {
return inServiceCountry;
}
public void setInServiceCountry(String inServiceCountry) {
this.inServiceCountry = inServiceCountry;
}
public String getTrainingStatus() {
return trainingStatus;
}
public void setTrainingStatus(String trainingStatus) {
this.trainingStatus = trainingStatus;
}
}
Комментарии:
1. Вы можете использовать список ArrayList в качестве потока, вызвав «.stream()» в своем списке ArrayList. Это открывает множество методов функционального программирования для использования. Вы захотите использовать «.filter(Предикат предиката)» здесь, он должен более или менее идеально соответствовать вашим потребностям. После того, как вы закончите с вашим «.stream ()», я полагаю, вам понадобится новый список массивов не зарезервированных животных, поэтому вы вызовете «.collect(Коллектор коллектора)» для реализаций JDK до 16. Пример до 16:
dogList.stream().filter(d -> !d.reversed).collect(Collectors.toList)
. Пример >16:dogList.stream().filter(d -> !d.reserved).toList()
Ответ №1:
Вы не должны использовать ==
его для проверки равенства строк. Воспользуйся equals
if (listType == "dog") {
System.out.println(dogList.toString());
}
else if(listType == "monkey") {
System.out.println(monkeyList.toString());
}
Изменить на
if ("dog".equals(listType)) {
System.out.println(dogList.toString());
}
else if("monkey".equals(listType)) {
System.out.println(monkeyList.toString());
}
Ответ №2:
Как всегда говорил мне мой отец,… «Самый простой способ что-то сделать-это не делать этого». Шучу,… в основном, вместо того, чтобы искать свой список, создайте новый. в разделе обезьяна и собака есть доступный список(); или все, что вы хотите. когда ваш пользователь заполняет данные сеттером, просто используйте if/else, чтобы также добавить доступное животное в ваш новый список. (приведенный ниже код-это просто зарезервированный сеттер, все остальные над ним со строкой добавления вверху.)
System.out.println("Is " name "reserved?");
if (scan.next().equalsIgnoreCase("yes")) {
dog.setReserved(true);
} else {
dog.setReserved(false);
RescueAnimal animal = new RescueAnimal();
availableList.add(-i, animal);