Driver Java Animal Reserve - java

Unsure of where my code is failing, and where I should be going next with it. I need a fully functional loop menu, that seems to work so far, in which I am able to do the options the menu displays. This includes adding to lists and checking lists. I also am having an issue in which the dog list is not displaying the list of dogs by their name or information, but rather their space. Any help would be greatly appreciated.
// Complete intakeNewMonkey
//Instantiate and add the new monkey to the appropriate list
// 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 new monkey's name?");
String name = scanner.nextLine();
for (Monkey monkey: monkeyList) {
if(monkey.getName().equalsIgnoreCase(name)) {
System.out.println("\n\nThis monkey is already in our system.\n\n");
return;
}
}
System.out.println("What is the monkey's tail length?");
String tailLength = scanner.nextLine();
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("What is the monkey's acquisition date?");
String acquisitionDate = scanner.nextLine();
System.out.println("What is the monkey's acquisition country?");
String acquisitionCountry = scanner.nextLine();
System.out.println("What is the monkey's training status?");
String trainingStatus = scanner.nextLine();
System.out.println("Is the monkey reserved? <enter true or false>");
boolean reservedBoolean = scanner.nextBoolean();
System.out.println("What is the monkey's service country?");
String serviceCountry = scanner.nextLine();
System.out.println("What is the monkey's body length?");
String bodyLength = scanner.nextLine();
System.out.println("What is the monkey's height?");
String height = scanner.nextLine();
System.out.println("What is the monkey's species?");
String species = scanner.nextLine();
}
// 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("Enter animal type");
String type = scanner.nextLine();
if (type.equals("Monkey") || type.equals("monkey")) {
for (int i = 0; i < monkeyList.size(); i++) {
if (!monkeyList.get(i).getReserved());
System.out.println(monkeyList.get(i));
}
System.out.println("Enter name: ");
String name = scanner.nextLine();
for (Monkey obj: monkeyList) {
if (obj.name.equals(name)) {
obj.reserved = true;
return;
}
}
System.out.println("Monkey not found in list");
}
if (type.equals("Dog") || type.equals("dog")) {
for (int i = 0; i < dogList.size(); i++) {
if (dogList.get(i).getReserved())
System.out.println(dogList.get(i));
}
System.out.println("Enter name: ");
String name = scanner.nextLine();
for (Dog obj: dogList) {
if (obj.name.equals(name)) {
obj.reserved = true;
return;
}
}
System.out.println("Dog not found in list");
}
}
// 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() {
System.out.println("The method printAnimals needs to be implemented");
}

You need to override the toString() class provided by the Object class. You can do this by writing something like
#Override
public String toString() {
return "Name: " + this.name + ". Gender " + this.gender "." // and so on
}

Related

searching in arraylist always not found

no matter what I use indexof() or contains or .equals() changing everything to uppercase or to lowercase It always return false and not found can someone please tell me what is going on?
class Students{
private ArrayList<String> snames;
private String tname;
//this one combines both question 2 and 4.
public Students(String tname){
snames=new ArrayList<>();
this.tname=tname;
}
public String gettname(){return tname;}
public ArrayList<String> getsnames(){return snames;}
public void addStudent(String name){
snames.add(name);
}
public boolean studentExists(String name){
boolean e=false;
for(String i:snames){
if(i.contains(name)){
e=true;
}
}
return e;
}
}
public class Main
{
public static void main(String[] args) throws IOException{
Scanner k=new Scanner(System.in);
out.println("what is your name?");
String name=k.nextLine();
out.println(name.toUpperCase());
Students s=new Students(name);
out.println("enter student name");
String snames=k.nextLine();
while(snames!="."){
out.println("enter student name");
snames=k.nextLine();
s.addStudent(snames);
if (snames.equals("."))
break;
}
out.println("who u want to find");
String target=k.nextLine();
boolean exist=s.studentExists(target);
if(exist==true){
out.println("Found student");
}
else out.println("Student not found.");
out.println(exist);
}
}
no matter what I use indexof() or contains or .equals() changing everything to uppercase or to lowercase It always return false and not found can someone please tell me what is going on?
You have a logic issue...
out.println("enter student name");
String snames = k.nextLine();
while (snames != ".") {
out.println("enter student name");
snames = k.nextLine();
s.addStudent(snames);
if (snames.equals(".")) {
break;
}
}
You...
Prompt for the name
Read the next line of input
Check to see if it's the exit condition (by the way, snames != "." is wrong, it should be !".".equals(snames)
You prompt them to enter the name
You read the input
You write the input to Students
You check for the exit condition ... again
So, between 3 and 4, you never write what was first entered by the user, so, if you only enter
enter student name
jack
enter student name
.
Only . will be added to the list
Instead, you should be doing something more like...
Scanner scanner = new Scanner(System.in);
Students students = new Students("Test");
String name = ".";
do {
System.out.print("enter student name (or \".\" to exit) ");
name = scanner.nextLine();
if (!name.equals(".")) {
students.addStudent(name);
}
} while (!name.equals("."));
do {
System.out.print("who u want to find (or \".\" to exit) ");
name = scanner.nextLine();
if (!name.equals(".")) {
if (students.studentExists(name)) {
System.out.println("Match found");
} else {
System.out.println("Match not found");
}
}
} while (!name.equals("."));
The important point here is to make sure when you ask for input, you are actually writing it the list, unless it's the exit value (ie .)
The code is bad-structured, and the first snames is never added to the ArrayList.
See the codes below in class Main:
public static void main(String[] args) throws IOException {
// ignore the teacher name part
Students s = new Students(name);
// when the first snames is received,
System.out.println("enter student name");
String snames = k.nextLine();
while (snames != ".") {
// the name is not saved, but another snames is received.
System.out.println("enter student name");
snames = k.nextLine();
System.out.println(snames);
s.addStudent(snames);
// the "." is also saved as well.
if (snames.equals("."))
break;
}
}
}
I would suggest modifying the while loop into something like this:
Students student = new Students(tname);
// no need to get scanner output before loop
String sname;
do {
System.out.println("enter student name");
sname = scanner.nextLine();
System.out.println(sname);
student.addStudent(sname);
} while (!sname.equals("."));
Hope this answer helps you well.

Print a value from 2d array in Java

I am working on a program that allows a user to add values to a 2d array and then search the array and display the value. The information is being stored properly, but all I can get to display is the animal name and not the food. Before I get grilled I've searched and implemented a bunch of different methods trying to get the correct output. I'm sure my error is pretty simple if someone could just help me understand, thanks!
/*This program will allow a user to enter information into the zoo
or search by animal for the type of food it eats*/
import java.util.Scanner;
class zoo {
//create array
static String[][] animalFood;
String[][] addArray(int x) {
animalFood = new String[x][2];
Scanner in = new Scanner(System.in);
//loop through array and add amount of items user chose
for (int row = 0; row < animalFood.length; row++){
System.out.print("Enter an animal name: ");
animalFood[row][0] = in.nextLine();
System.out.print("Enter the food the animal eats: ");
animalFood[row][1] = in.nextLine();
}
System.out.println("Thank you for adding information to the zoo!");
System.out.println("You entered the following information: ");
//loop through and print the informationa added
for(int i = 0; i < animalFood.length; i++)
{
for(int j = 0; j < animalFood[i].length; j++)
{
System.out.print(animalFood[i][j]);
if(j < animalFood[i].length - 1) System.out.print(" - ");
}
System.out.println();
}
//prompt the user to search or quit
System.out.println("Please enter the name of the animal to search for or Q to quit: ");
String animalName = in.nextLine();
animalName = animalName.toUpperCase();
if(animalName.equals("Q")){
System.out.println("Thanks for using the program!");
}
else {
searchArray(animalName);
}
return animalFood;
}
String[][] searchArray(String name) {
String matchResult = "There was no " + name + " found in the zoo!";
String itemToMatch = name.toUpperCase();
String arrayItem = "";
String food = "";
for (int i = 0; i < animalFood.length; i++) {
for (int j = 0; j < animalFood.length; j++) {
arrayItem = animalFood[i][j];
arrayItem = arrayItem.toUpperCase();
if(arrayItem.equals(itemToMatch)){
matchResult = "The animal " + name + " was found in the zoo! It eats " + animalFood[j];
}
else {
//nothing found
}
}
}
System.out.println(matchResult);
if (food != null) {
System.out.println(food);
}
return animalFood;
}
//constructor
public zoo() {
}
//overloaded constructor
public zoo(int x) {
int number = x;
animalFood = addArray(x);
}
//method to get users choice
public static int menu() {
int selection;
Scanner input = new Scanner(System.in);
System.out.println("Please make a choice in the menu below");
System.out.println("-------------------------\n");
System.out.println("1 - Add animals and the food they eat.");
System.out.println("2 - Search for an animal in the zoo.");
System.out.println("3 - Exit the program");
selection = input.nextInt();
return selection;
}
//main method
public static void main(String[] args) {
//create a new object
zoo myZoo = new zoo();
//variables and scanner
int userChoice;
int numberAnimals;
String animalName = "";
Scanner input = new Scanner(System.in);
//call the menu
userChoice = menu();
//actions based on user choice
if (userChoice == 1) {
System.out.println("How many animals would you like to enter information for?");
numberAnimals = input.nextInt();
myZoo.addArray(numberAnimals);
}
if (userChoice == 2) {
System.out.println("Please enter the name of the animal to search for: ");
animalName = input.nextLine();
myZoo.searchArray(animalName);
}
if (userChoice == 3) {
System.out.println("Thank you for using the program!");
}
}
}
It looks to me like your problem is in searchArray. Your nested for loops are iterating over the size of only one dimension of the array:
for (int i = 0; i < animalFood.length; i++) {
for (int j = 0; j < animalFood.length; j++) {
...
}
}
Replace animalFood.length with animalFood[i].length, like you did correctly in the addArray method.
EDIT
It also looks like your output method is incorrect.
matchResult = "The animal " + name + " was found in the zoo! It eats " + animalFood[j];
In this line, animalFood[j] should be animalFood[i][j]. The strange output you're seeing is Java's attempt at converting an array into a String.
2nd Edit
After examining the addArray method, it seems I've made an incorrect assumption about your array. It appears your array is structured such that each index has 2 items, the animal, and its food. So it looks like so:
animalFood[0][0] = 'Cat'
animalFood[0][1] = 'Cat food'
animalFood[1][0] = 'Dog'
animalFood[1][1] = 'Dog food'
etc.
If this is the case, then you're going to want to change your loop to only iterate over the outer index. This means removing the inner for loop inside of searchArray. Then, you're only going to compare the first index of the inner array to the item you want to match, and if there's a match, then the food will be the second index. I'll leave implementation up to you (since this looks like a homework question). If something I've said here sounds wrong, let me know.

ArrayList<String> delete query

Here's my output:
-----Query-----
[1]Update
[2]Delete
[3]Search
[4]Show
Choose Query:1
Enter Your Student ID:1
Enter Your First Name: Respo
Enter Your Middle Name: Topher
Enter Your Last Name: Raspo
Do you want to back to Query?(Yes/No)
Yes
-----Query-----
[1]Update
[2]Delete
[3]Search
[4]Show
Choose Query: 4
12
Christopher
Reposo
Porras
1
Respo
Topher
Raspo
As you can see in the picture I'm trying to make a simple little system without database but using ArrayList to contain those data now my problem is in the Delete Query. Now in Delete Query I tell the user to type the student number which is 1 then delete the information of it and its contain which is first name, middle name, last name But I don't have much logic in ArrayList to do such thing. By the way is it possible to use only One ArrayList in this case or I need to make many array list to solve my problem.
public static void main(String[] args) {
//initialize Scanner for input process
Scanner scan = new Scanner(System.in);
//initialize needs variable
List<String> list = new ArrayList<String>();
int choose,chooseQuery;
String chooseYesOrNo = " ";
String chooseYesOrNo2 = " ";
do {
//Startup Program
System.out.println("=====-----LibrarySystem-----=====");
System.out.println("[1]Student Information");
System.out.println("[2]Book Information");
System.out.print("Choose Table:");
choose = scan.nextInt();
do {
if(choose == 1) {
System.out.println("-----Query-----");
System.out.println("[1]Update");
System.out.println("[2]Delete");
System.out.println("[3]Search");
System.out.println("[4]Show");
//reserved
//reserved
System.out.print("Choose Query:");
chooseQuery = scan.nextInt();
if(chooseQuery == 1) {
System.out.print("Enter Your Student ID:");
String id = scan.next();
list.add(id);
System.out.print("Enter Your First Name:");
String name = scan.next();
list.add(name);
System.out.print("Enter Your Middle Name:");
String middle_name = scan.next();
list.add(middle_name);
System.out.print("Enter Your Last Name:");
String last_name = scan.next();
list.add(last_name);
System.out.println("Do you want to back to Query?(Yes/No)");
chooseYesOrNo = scan.next();
} else if (chooseQuery == 2) { //Delete Query
System.out.print("Enter Student ID:");
String find_id = scan.next();
} else if(chooseQuery == 3) { //Search Query
} else if(chooseQuery == 4) { //Show Query
for (String s : list) {
System.out.println(s);
}
}
}
} while(chooseYesOrNo.equals("Yes"));
System.out.println("Do you want to get back at tables?(Yes/No)");
chooseYesOrNo2 = scan.next();
} while(chooseYesOrNo2.equals("Yes"));
System.out.println("-----=====Program Terminated=====-----");
}
Create Student object which contains all the fields you need (student id, name, etc)
class Student {
int studentId;
String firstname;
String middlename;
String lastname;
}
Have one array list for Student objects
java.util.List<Student> list = new java.util.ArrayList<Student>();
When Delete operation is selected, iterate through your list to find the object and remove it. Here's nice blog about ways to iterate through arraylist. My favorite method is as follows:
for (Student std:list) {
if (std.studentId == targetId) {
list.remove(std);
break; //since you've removed target, you can exit the loop
}
}

Using user input value to display a specific object from an array list

I am trying to create a program where the user inputs animal pertinent values, which then create animal Objects, which are then saved into an array list. The area I am having trouble with is shown below. After the Array list is populated, I cannot figure out how to use the user input (select) to find that values index within the array list. (int index = animalList.indexOf(?))
Would appreciate any help
Scanner in = new Scanner(System.in);
List <Animal> animalList = new ArrayList <Animal>();
char ans;
do{ // User input
Animal animal = new Animal(); // arraylist
System.out.println("Animal's 'common' name: ");
animal.setName(in.next());
System.out.println("Animal's class: ");
animal.setAnmlClass(in.next());
System.out.println("Vertabrate or Invertabrate: ");
animal.setCharVert(in.next());
System.out.println("Warm or Cold blooded: ");
animal.setCharBld(in.next());
System.out.println("Animal's habitat (general): ");
animal.setCharHab(in.next());
System.out.println("Would you like to enter in a new animal (y/n)? ");
String answer = in.next();
ans = answer.charAt(0);
animalList.add(animal);
}while(ans == 'y');
System.out.println("Enter the animal you wish to view: ");
String select = in.next();
System.out.println(select);
int index = animalList.indexOf( ? );
System.out.println(index);
You might consider making a HashTable instead of a List, with the animal name as the key.
Unfortunately, you need a custom method for this with a while loop:
public int getIndexWithName(List<Animal> animals, String name){
for (int index = 0; index < animals.size(); index++){
if (name.equals(animals.get(index).getName())){
return index;
}
}
return -1;
}
And use this:
int index = getIndexWithName(animalList, select);
//Do some validation check
if (index < 0){
//Give some error message
System.out.println("That's not a common name I recognize!");
}
System.out.println("Enter the name of the animal you wish to view: ");
String select = in.next();
System.out.println(select); // Check that your toString() its proper
//There's not a straight way to find each animal's index
// so you 'll have to write an int getIndex(select) method to do that and then you 'll call it
int index = getIndext(select);
System.out.println("The animal you chose has index: "+index);
Create a HashMap<String, Animal> that maps an animal's name to the object.
Scanner in = new Scanner(System.in);
List <Animal> animalList = new ArrayList <Animal>();
Map<String, Animal> map = new HashMap<>();
char ans;
do{ // User input
Animal animal = new Animal(); // arraylist
System.out.println("Animal's 'common' name: ");
String name = in.next();
animal.setName(name);
map.put(name, animal);
System.out.println("Animal's class: ");
animal.setAnmlClass(in.next());
System.out.println("Vertabrate or Invertabrate: ");
animal.setCharVert(in.next());
System.out.println("Warm or Cold blooded: ");
animal.setCharBld(in.next());
System.out.println("Animal's habitat (general): ");
animal.setCharHab(in.next());
System.out.println("Would you like to enter in a new animal (y/n)? ");
String answer = in.next();
ans = answer.charAt(0);
animalList.add(animal);
}while(ans == 'y');
System.out.println("Enter the animal you wish to view: ");
String select = in.next();
System.out.println(map.get(select));
With help from Roel & Theodora, I ended up with this. It may not be the cleanest or "prettiest" way to do this, but it works with no issues.
System.out.println("Enter the animal you wish to view: ");
String select = in.next();
for (int index = 0; index < animalList.size(); index++){
if (select.equals(animalList.get(index).getName())){
System.out.println(index);
System.out.format("%n"); // aesthetic break
System.out.print(animalList.get(index).getName()+": ");
System.out.print(animalList.get(index).getAnmlClass()+", ");
System.out.print(animalList.get(index).getCharVert()+", ");
System.out.print(animalList.get(index).getCharBld()+" Blooded, ");
System.out.print(animalList.get(index).getCharHab()+" Terrain");
System.out.format("%n"); // aesthetic break
}
else{
System.out.println("The Zoo does not house that animal currently");
}
}

Scanning different types of variables in one line

As the title says, I would like to scan the whole line of input just using one input from user. The input should be like "Eric 22 1".
If nextString() shouldn't be used that way, should I just use hasNext?
JAVA CODE :
import java.util.Scanner;
public class tugas1
{
public static void main(String []args)
{
String name;
int age;
boolean sex;
Scanner sc = new Scanner(System.in);
System.out.println("Please input your name, age, and sex(input 1 if you are a male, or 0 if you are a female) :");
name = sc.nextString();
age = sc.nextInt();
sex = sc.nextBoolean();
if(isString(name))
{
if(isInteger(age))
{
if(isBoolean(sex))
{
System.out.println("Correct format. You are :" +name);
}
else
{
System.out.println("Please input the age in integer");
}
}
else
{
System.out.println("Please input the age in integer");
}
}
else
{
System.out.println("Please input the name in string");
}
}
}
After adding and editing the lines :
System.out.println("Please input your name, age, and sex(input 1 if you are a male, or 0 if you are a female) :");
String input = sc.nextLine();
String[] inputAfterSplit = input.split(" ");
String name = inputAfterSplit[0];
int age = Integer.parseInt(inputAfterSplit[1]);
boolean sex = Boolean.parseBoolean(inputAfterSplit[2]);
I would like to add if(name instanceof String). I haven't touched Java since a long time and I forgot is that the way of using instanceof, or is that wrong?
The point is I want to compare if the input var is in int or string or bool.
if(name instanceof String)
{
if(age instanceof Integer)
{
if(sex instanceof Boolean)
{
System.out.println("All checked out")
}
else
{
System.out.println("Not boolean")
}
else
{
System.out.println("Not int")
}
System.out.println("Not string")
}
Will these lines work?
Please input your name, age, and sex
As you need to insert values in specific sequence.
Use nextLine() and perform split
For Example:"Abc 123 true 12.5 M"
String s[]=line.split(" ");
And you will have
s[0]="Abc"
s[1]="123"
s[2]="true"
s[3]="12.5"
s[4]="M"
Than parse them to required type.
String first=s[0];
int second=Integer.parseInt(s[1].trim());
boolean third=Boolean.parseBoolean(s[2].trim());
double forth=Double.parseDouble(s[3].trim());
char fifth=s[4].charAt(0);
As your code suggest and as David said you can change just this
name = sc.next();//will read next token
age = sc.nextInt();
sex = (sc.next()).charAt(0);//change sex to character for M and F
//or //sex = sc.nextInt();//change it to int
first thing when we use scanner , we dont have a method called nextString()
so instead we must use next() which is to read string.
secondly when you want to read whole line then use nextLine() which will read entire line in the form of text and put it in a string.
now the String which is read as entire line can be split based on split character(assume it is space in our case)
then get the string array and parse each element to required type.
better if we use try/catch while parsing so that we can catch exception for unwanted format for the input and throw it to user.
sample code without try/catch but you use try/catch as per your need
Scanner sc = new Scanner(System.in);
System.out.println("Please input your name, age, and sex(input 1 if you are a male, or 0 if you are a female) :");
String input = sc.nextLine();
String[] inputAfterSplit = input.split(" ");
String firstParam = inputAfterSplit[0];
int secondParam=Integer.parseInt(inputAfterSplit[1]);
boolean thirdParam=Boolean.parseBoolean(inputAfterSplit[2]);
Reworked it all, this is the remake of the code just in case people are having same problem as mine..
int in the delcaration should be changed into Integer
import java.util.Scanner;
import java.lang.*;
public class tugas1
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Input number of line :");
int lineNum = sc.nextInt();
String[] name = new String[lineNum];
Integer[] age = new Integer[lineNum];
String[] gender = new String[lineNum];
System.out.println("Please input your name, age, and gender(Male/Female) \n(Separate each line by an enter) :");
for ( int i = 0; i < lineNum; i++)
{
System.out.print("Line " + (i+1) + " : ");
name[i] = sc.next();
age[i] = sc.nextInt();
gender[i] = sc.next();
}
for ( int j = 0; j < lineNum; j++ )
{
if (name[j] instanceof String)
{
if (age[j] instanceof Integer)
{
if (gender[j] instanceof String)
{
System.out.println("Person #" + (j+1) + " is " + name[j] + ", with age of " + age[j] + " years old, and gender " + gender[j]);
}
else
{
System.out.println("Gender is missing");
}
}
else
{
System.out.println("Age and Gender are");
}
}
else
{
System.out.println("Name, Age and Gender are missing");
}
}
}
}

Categories

Resources