Replacing Position in Array Amongst Other Methods - java

Firstly - I thank anyone who takes the time to actually look at this since I feel like it's a rather annoying request.
I just completed a large challenge at the end of a series of Java 101 videos. The challenge is to design a guest list method ( as in for a restaurant or a party ) and some features along with it. This is really the first time I've written anything with multiple methods.
As the final step in this challenge, I need to design a method that allows the user to insert a new guest at a certain position while not removing any other guests. In other words, inserting a new guest and shifting the remaining guests downwards by a single index.
The issue I have is that the new guest is always inserted not only for the position I want, but also the position one after. It inserts itself twice and ends up over-writing the previous guest in the process.
import java.util.Scanner;
import java.io.*;
import java.lang.*;
import java.util.*;
public class GuestList_Edited {
public static void main(String[] args) {
// Setup for array, setup for scanner
String[] guests = new String[11];
Scanner scanner = new Scanner(System.in);
// A method to put these here so we don't always have to add guests. This method automatically inserts five guests into the guest list.
InsertNames(guests);
// Do-while loop to make sure that this menu screen shows up every time asking us what we want to do.
// It also makes certain that the menu shows up when we initially run the program.
do {
displayMenu(guests);
// This must remain in main for the rest of the program to reference it.
int option = getOption();
// If loop that will allow people to add guests
if (option == 1) {
addGuest(guests);
} else if (option == 2) {
RemoveGuest(guests);
} else if (option == 3) {
RenameGuest(guests);
} else if (option == 4) {
insertGuest(guests);
} else if (option == 5) {
System.out.println("Exiting...");
break;
}
} while (true);
}
// This displays the starting menu
public static void displayMenu(String SentArr[]) {
System.out.println("-------------");
System.out.println(" - Guests & Menu - ");
System.out.println();
GuestsMethod(SentArr); // Makes all null values equal to --
System.out.println();
System.out.println("1 - Add Guest");
System.out.println("2 - Remove Guest");
System.out.println("3 - Rename guest");
System.out.println("4 - Insert new guest at certain position");
System.out.println("5 - Exit");
System.out.println();
}
// This prints all the guests on the guest list and also adjusts the guest list when a guest is removed
public static void GuestsMethod(String RecievedArr[]) {
// If loop which prints out all guests on the list.
// "Null" will be printed out for all empty slots.
for (int i = 0; i < RecievedArr.length - 1; i++) {
// Make all null values and values after the first null value shift up in the array.
if (RecievedArr[i] == null) {
RecievedArr[i] = RecievedArr[i + 1];
RecievedArr[i + 1] = null;
}
// Make all null's equal to a string value.
if (RecievedArr[i] == null) {
RecievedArr[i] = " ";
}
// If values are not equal to a blank string value, assign a number.
if (RecievedArr[i] != " ") {
System.out.println((i + 1) + ". " + RecievedArr[i]);
}
// If the first value is a blank string value, then print the provided line.
if (RecievedArr[0] == " ") {
System.out.println("The guest list is empty.");
break;
}
}
}
// I've really got no idea what this does or why I need a method but the course I'm taking said to create a method for this.
// It gets the desired option from the user, as in to add a guest, remove a guest, etc.
static int getOption() {
Scanner scanner = new Scanner(System.in);
System.out.print("Option: ");
int Option = scanner.nextInt();
return Option;
}
// Allows users to add guests
public static String[] addGuest(String AddArr[]) {
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < AddArr.length; i++) {
// The below if statement allows the program to only ask for a name when a given space is "null", meaning empty.
if (AddArr[i] == " ") {
// so the loop runs until it hits a null value.
System.out.print("Name: ");
AddArr[i] = scanner.nextLine();
// Then that same value which was null will be replaced by the user's input
break;
}
}
return AddArr;
}
public static String[] RemoveGuest(String RemoveArr[]) {
Scanner scanner = new Scanner(System.in);
System.out.print("Number of guest: ");
int input = scanner.nextInt();
int number = input - 1;
// While loop to look for numbers that fit within array's range
while (number < -1 || number > 9) {
System.out.println("Trying to pull a fast one? No more funny games, give me a real number to work with.");
System.out.println(" ");
System.out.println("What is the number of the guest");
input = scanner.nextInt();
number = input - 1;
}
for (int i = 0; i < RemoveArr.length; i++) {
if (RemoveArr[number] != null) {
RemoveArr[number] = null;
break;
}
}
return RemoveArr;
}
// This inserts names into the array so we don't have to add guests everytime.
public static String[] InsertNames(String InsertNames[]) {
InsertNames[0] = "Jacob";
InsertNames[1] = "Edward";
InsertNames[2] = "Rose";
InsertNames[3] = "Molly";
InsertNames[4] = "Christopher";
// guests[5] = "Daniel";
// guests[6] = "Timblomothy";
// guests[7] = "Sablantha";
// guests[8] = "Tagranthra";
return InsertNames;
}
public static String[] RenameGuest(String RenamedGuests[]) {
Scanner scanner = new Scanner(System.in);
System.out.print("Number of guest: ");
int input = scanner.nextInt();
int number = input - 1;
// While loop to look for numbers that fit within array's range
while (number < -1 || number > 9) {
System.out.println("Trying to pull a fast one? No more funny games, give me a real number to work with.");
System.out.println(" ");
System.out.println("What is the number of the guest");
input = scanner.nextInt();
number = input - 1;
}
for (int i = 0; i < RenamedGuests.length; i++) {
if (RenamedGuests[number] != null) {
RenamedGuests[number] = null;
System.out.println("What would you like the guest's name to be?");
String NewName = scanner.next();
RenamedGuests[number] = NewName;
break;
}
}
return RenamedGuests;
}
// The final method which I am struggling with.
public static String[] insertGuest(String NewPositionArray[]) {
Scanner scanner = new Scanner(System.in);
System.out.print("Number: ");
int num = scanner.nextInt();
scanner.nextLine();
if (num >= 1 && num <= 10 && NewPositionArray[num - 1] != null)
System.out.print("Name: ");
String name = scanner.nextLine();
for (int i = 10; i > num - 1; i--) {
NewPositionArray[i] = NewPositionArray[i - 1];
NewPositionArray[num - 1] = name;
}
if (num < 0 || num > 10) {
System.out.println("\nError: There is no guest with that number.");
}
return NewPositionArray;
}
}
Once again, thanks. I realize I've probably done 1000 things wrong here. I appreciate your consideration.

I recommend you to declare ArrayList object instead of the normal array declaration; to avoid heavy work on the code where you can add an element into the ArrayList object with predefined add(int position, an element with your data type) method in a specific position and the ArrayList automatically will shift the rest elements to the right of it.
and for several reasons.
for more info about ArrayList in Java, please look at: -
Array vs ArrayList in Java
Which is faster amongst an Array and an ArrayList?
Here an example of add() method; which inserts the element in a specific position: -
Java.util.ArrayList.add() Method

Related

Take input of number of elements of an array, and input the array and display the odd and even elements of the array in their specified arrays

I have written the question I have to write the code for in the title but I am getting certain errors in my code.
The errors are:
line 7: numOfVal cannot be resolved or is not a field
line 23: numOfVal cannot be resolved to a variable
line 25: cannot invoke add(int) on the array type int[]
line 28: cannot invoke add(int) on the array type int[]
line 47: oddarray cannot be resolved to a variable
line 48: evenarray cannot be resolved to a variable
I would be very grateful if you could help me fix the errors in my code.
Thanks.
import java.util.Scanner;
public class CountEvenOddArray {
int[] mainarray;
void setInpLength(int numOfVal) {
this.numOfVal = numOfVal;
}
void setVal(int index,
int Val) {
this.mainarray[index] = Val;
}
void MainArrays() {
mainarray = new int[100];
}
void EvenOdds() {
int evenarray[] = new int[100];
int oddarray[] = new int[100];
for (int i = 0; i <numOfVal ; i++ ) {
if (mainarray[i]%2 == 0) {
evenarray = evenarray.add(mainarray[i]);
}
else {
oddarray = oddarray.add(mainarray[i]);
}
}
}
public static void main(String[] args) {
CountEvenOddArray abc = new CountEvenOddArray();
int numOfVal;
int mainarray[] = new int[100];
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of elements you want to store:");
numOfVal = sc.nextInt();
abc.setInpLength(numOfVal);
System.out.println("Enter the elements of the array: ");
for (int k = 0; k < numOfVal; k++ ) {
abc.setVal(k, sc.nextInt());
}
abc.EvenOdds();
sc.close();
System.out.println("The array with the odd elements is:" + oddarray);
System.out.println("The array with the even elements is:" + evenarray);
}
} ```
Here is a runnable example of how this task could be accomplished. You will notice that there are very few methods required. Having too many methods to carry out single simple tasks that can be accomplished with single lines of code just makes things harder to follow and bloats the application. Be sure to read the comments within the code:
import java.util.Scanner;
public class CountEvenOddArray {
// Class member variables:
private final String LS = System.lineSeparator();
private int[] mainArray;
// Startup main() method (Application entry point):
public static void main(String[] args) {
// App started this way to avoid the need for statics:
new CountEvenOddArray().startApp(args);
}
private void startApp(String[] args) {
/* Open a keyboard input stream. You only ever need one
of these in any console application. Do not close this
stream unless you know for sure that you will never need
it again during your application session otherwise, you
will need to restart the application to use it again.
The JVM will automatically close this resource when the
application ends. */
Scanner sc = new Scanner(System.in);
// Get the desired size of Main Array from User:
String numOfElems = "";
while(numOfElems.isEmpty()) {
System.out.println("Enter number of elements you want to store or");
System.out.print( "enter 'q' to quit: -> ");
numOfElems = sc.nextLine().trim();
// Is Quit desired?
if (numOfElems.equalsIgnoreCase("q")) {
// Yes....
System.out.println("Quiting - Bye Bye");
return; // Will force a return to main() and effectively end application.
}
// Entry Validation...
/* If the entry does not match a string representation of a
integer value. (See the isInteger() method below): */
if (!isInteger(numOfElems)) {
// Then inform the User and let him/her try again...
System.out.println("Invalid Entry! (" + numOfElems + ") Try again..." + LS);
numOfElems = ""; // Empty variable to ensure re-loop.
}
}
// If we made it the far, then the entry is valid!
// Convert the string input value to integer:
int numOfElements = Integer.parseInt(numOfElems);
// Initialize mainArray{}:
mainArray = new int[numOfElements];
// Have User enter the elements for the Array (with validation):
System.out.println();
System.out.println("Enter the elements of the array ('q' to quit):");
for (int i = 0; i < numOfElements; i++ ) {
// Prompt for each required mainArray[] Element:
String elem = "";
while (elem.isEmpty()) {
System.out.print("Enter Element #" + (i+1) + ": -> ");
elem = sc.nextLine().trim();
// Is Quit desired?
if (elem.equalsIgnoreCase("q")) {
// Yes....
System.out.println("Quiting - Bye Bye");
return; // Will force a return to main() and effectively end application.
}
// Entry Validation...
/* If the entry does not match a string representation of a
integer value. (See the isInteger() method below): */
if (!isInteger(elem)) {
// Then inform the User and let him/her try again...
System.out.println("Invalid Entry! (" + elem + ") Try again..." + LS);
elem = ""; // Empty variable to ensure re-loop.
}
}
// If we made it the far, then the entry is valid!
// Convert the string input value to integer element:
int element = Integer.parseInt(elem);
mainArray[i] = element;
}
/* mainArray[] is now initialized and filled. We will now create
the oddArray[] and evenArray[] from what is in the mainArray[]
but, because we have no idea what the User may have entered
for element values, there is no real viable way to create exact
fixed length int[] odd or even arrays unless we count them first.
This would require additional iterations basically meaning, we
are doing the job twice. We can get around this by placing our
odd/even results into a couple of List<Integer> Lists (which can
grow dynamically) then converting them to array later (if desired): */
java.util.List<Integer> odd = new java.util.ArrayList<>();
java.util.List<Integer> even = new java.util.ArrayList<>();
/* Determine Odd or Even value elements within the mainArray[]
and place those values into the appropriate odd or even Lists. */
evenOdds(odd, even);
// Convert Lists to int[] Arrays....
// Convert List<Integer> odd to oddArray[]:
int[] oddArray = odd.stream().mapToInt(d -> d).toArray();
// Convert List<Integer> even to evenArray[]:
int[] evenArray = even.stream().mapToInt(d -> d).toArray();
// Display the oddArray[] and the evenArray[]...
System.out.println();
System.out.println(oddArray.length + " odd elements are in the oddArray[]: -> "
+ java.util.Arrays.toString(oddArray));
System.out.println(evenArray.length + " even elements are in the evenArray[]: -> "
+ java.util.Arrays.toString(evenArray));
}
/* Method to determine Odd or Even value elements within the mainArray[]
and place those values into the appropriate odd or even Lists. The
Lists are added to by way of reference to them therefore no returnable
objects are required.
*/
private void evenOdds(java.util.List<Integer> odd, java.util.List<Integer> even ) {
for (int i = 0; i < mainArray.length ; i++ ) {
if (mainArray[i] % 2 == 0) {
even.add(mainArray[i]);
}
else {
odd.add(mainArray[i]);
}
}
}
public boolean isInteger(String value) {
boolean result = true; // Assume true:
// Is value null or empty?
if (value == null || value.trim().isEmpty()) {
result = false;
}
/* Is value a match to a string representation of
a integer value? */
else if (!value.matches("\\d+")) {
result = false;
}
// Does value actually fall within the relm of an `int` data type?
else {
long lng = Long.parseLong(value);
if (lng > Integer.MAX_VALUE || lng < Integer.MIN_VALUE) {
result = false;
}
}
return result;
}
}
If run and your entries are like this within the Console Window:
Enter number of elements you want to store or
enter 'q' to quit: -> 5
Enter the elements of the array ('q' to quit):
Enter Element #1: -> 1
Enter Element #2: -> 3
Enter Element #3: -> 2
Enter Element #4: -> 5
Enter Element #5: -> 4
You should see something like this:
3 odd elements are in the oddArray[]: -> [1, 3, 5]
2 even elements are in the evenArray[]: -> [2, 4]

i want to display every number entered in my while loop.so how can i do this

must create a java application that will determine and display sum of numbers as entered by the user.The summation must take place so long the user wants to.when program ends the summation must be displayed as follows
e.g say the user enters 3 numbers
10 + 12+ 3=25
and you must use a while loop
Here's a function to do just that. Just call the function whenever you need.
Ex: System.out.println(parseSum("10 + 12+ 3")) → 25
public static int parseSum(String input) {
// Removes spaces
input = input.replace(" ", "");
int total = 0;
String num = "";
int letter = 0;
// Loop through each letter of input
while (letter < input.length()) {
// Checks if letter is a number
if (input.substring(letter, letter+1).matches(".*[0-9].*")) {
// Adds that character to String
num += input.charAt(letter);
} else {
// If the character is not a number, it turns the String to an integer and adds it to the total
total += Integer.valueOf(num);
num = "";
}
letter++;
}
total += Integer.valueOf(num);
return total;
}
The while loop is essentially a for loop though. Is there a specific reason why you needed it to be a while loop?
There is a lot of ways to achieve this. Here an example of code that could be improve (for example by catching an InputMismatchException if the user doesn't enter a number).
Please for the next time, post what you have tried and where you stuck on.
public static void main (String[] args) {
boolean playAgain = true;
while(playAgain) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the first number : ");
int nb1 = sc.nextInt();
System.out.println("Ok! I got it! Please enter the second number : ");
int nb2 = sc.nextInt();
System.out.println("Great! Please enter the third and last number : ");
int nb3 = sc.nextInt();
int sum = nb1+nb2+nb3;
System.out.println("result==>"+nb1+"+"+nb2+"+"+nb3+"="+sum);
boolean validResponse = false;
while(!validResponse) {
System.out.println("Do you want to continue ? y/n");
String response = sc.next();
if(response.equals("n")) {
System.out.println("Thank you! see you next time :)");
playAgain = false;
validResponse = true;
} else if(response.equals("y")) {
playAgain = true;
validResponse = true;
} else {
System.out.println("Sorry, I didn't get it!");
}
}
}
}

How to find max number and occurrences

So I'm learn java for the first time and can't seem to figure how to set up a while loop properly .
my assignment is Write a program that reads integers, finds the largest of them, and counts its occurrences.
But I have 2 problems and some handicaps. I'm not allowed to use an array or list because we haven't learned that, So how do you take multiple inputs from the user on the same line . I posted what I can up so far . I am also having a problem with getting the loop to work . I am not sure what to set the the while condition not equal to create a sential Value. I tried if the user input is 0 put I cant use user input because its inside the while statement . Side note I don't think a loop is even needed to create this in the first place couldn't I just use a chain of if else statement to accomplish this .
package myjavaprojects2;
import java.util.*;
public class Max_number_count {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int count = 0;
int max = 1;
System.out.print("Enter a Integer:");
int userInput = input.nextInt();
while ( userInput != 0) {
if (userInput > max) {
int temp = userInput;
userInput = max;
max = temp;
} else if (userInput == max) {
count++ ;
}
System.out.println("The max number is " + max );
System.out.println("The count is " + count );
}
}
}
So how do you take multiple inputs from the user on the same line .
You can use scanner and nextInput method as in your code. However, because nextInt only read 1 value separated by white space at a time, you need to re-assign your userInput varible at the end of while loop to update the current processing value as below.
int userInput = input.nextInt();
while ( userInput != 0) {
//all above logic
userInput = input.nextInt();
}
The code:-
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int max = 0, count = 0, num;
System.out.println("Enter numbers:-");
while ((num = sc.nextInt()) != 0) {
if (num > max) {
max = num;
count = 1;
} else if (num == max) {
count++;
}
}
System.out.println("\nCount of maximum number = "+count);
}
}
And you don't have to use ArrayList or Array. Just keep inputting numbers till you get 0.
You can implement this with a single loop. The traditional concise pattern for doing so involves the fact that assignment resolved to the value assigned. Thus your loop can use (x = input.nextInt()) != 0 to terminate (handling exceptions, and non-integer input left as an exercise for the reader). Remember to display the max and count after the loop and reset the count to 1 when you find a new max. Also, I would default max to Integer.MIN_VALUE (not 1). That leaves the code looking something like
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a Integer:");
int count = 0, max = Integer.MIN_VALUE, userInput;
while ((userInput = input.nextInt()) != 0) {
if (userInput > max) {
max = userInput;
count = 1;
} else if (userInput == max) {
count++;
}
}
System.out.println("The max number is " + max);
System.out.println("The count is " + count);
}

Store user input in array multiple times

I'm working on a project which...
Allows the user to input 4 numbers that are then stored in an array for later use. I also want every time the user decided to continue the program, it creates a new array which can be compared to later to get the highest average, highest, and lowest values.
The code is not done and I know there are some things that still need some work. I just provided the whole code for reference.
I'm just looking for some direction on the arrays part.
*I believe I am supposed to be using a 2-D array but I'm confused on where to start. If I need to explain more please let me know. (I included as many comments in my code just in case.)
I tried converting the inputDigit(); method to accept a 2-D array but can't figure it out.
If this question has been answered before please redirect me to the appropriate link.
Thank you!
package littleproject;
import java.util.InputMismatchException;
import java.util.Scanner;
public class littleProject {
public static void main(String[] args) {
// Scanner designed to take user input
Scanner input = new Scanner(System.in);
// yesOrNo String keeps while loop running
String yesOrNo = "y";
while (yesOrNo.equalsIgnoreCase("y")) {
double[][] arrayStorage = inputDigit(input, "Enter a number: ");
System.out.println();
displayCurrentCycle();
System.out.println();
yesOrNo = askToContinue(input);
System.out.println();
displayAll();
System.out.println();
if (yesOrNo.equalsIgnoreCase("y") || yesOrNo.equalsIgnoreCase("n")) {
System.out.println("You have exited the program."
+ " \nThank you for your time.");
}
}
}
// This method gets doubles and stores then in a 4 spaced array
public static double[][] inputDigit(Scanner input, String prompt) {
// Creates a 4 spaced array
double array[][] = new double[arrayNum][4];
for (int counterWhole = 0; counterWhole < array.length; counterWhole++){
// For loop that stores each input by user
for (int counter = 0; counter < array.length; counter++) {
System.out.print(prompt);
// Try/catch that executes max and min restriction and catches
// a InputMismatchException while returning the array
try {
array[counter] = input.nextDouble();
if (array[counter] <= 1000){
System.out.println("Next...");
} else if (array[counter] >= -100){
System.out.println("Next...");
} else {
System.out.println("Error!\nEnter a number greater or equal to -100 and"
+ "less or equal to 1000.");
}
} catch (InputMismatchException e){
System.out.println("Error! Please enter a digit.");
counter--; // This is designed to backup the counter so the correct variable can be input into the array
input.next();
}
}
}
return array;
}
// This will display the current cycle of numbers and format all the data
// and display it appropriatly
public static void displayCurrentCycle() {
int averageValue = 23; // Filler Variables to make sure code was printing
int highestValue = 23;
int lowestValue = 23;
System.out.println(\n--------------------------------"
+ "\nAverage - " + averageValue
+ "\nHighest - " + highestValue
+ "\nLowest - " + lowestValue);
}
public static void displayAll() {
int fullAverageValue = 12; // Filler Variables to make sure code was printing
int fullHighestValue = 12;
int fullLowestValue = 12;
System.out.println(" RESULTS FOR ALL NUMBER CYCLES"
+ "\n--------------------------------"
+ "\nAverage Value - " + fullAverageValue
+ "\nHighest Value - " + fullHighestValue
+ "\nLowest Value - " + fullLowestValue);
}
// This is a basic askToContinue question for the user to decide
public static String askToContinue(Scanner input) {
boolean loop = true;
String choice;
System.out.print("Continue? (y/n): ");
do {
choice = input.next();
if (choice.equalsIgnoreCase("y") || choice.equalsIgnoreCase("n")) {
System.out.println();
System.out.println("Final results are listed below.");
loop = false;
} else {
System.out.print("Please type 'Y' or 'N': ");
}
} while (loop);
return choice;
}
}
As far as is understood, your program asks the user to input four digits. This process may repeat and you want to have access to all entered numbers. You're just asking how you may store these.
I would store each set of entered numbers as an array of size four.
Each of those arrays is then added to one list of arrays.
A list of arrays in contrast to a two-dimensional array provides the flexibility to dynamically add new arrays.
We store the digits that the user inputs in array of size 4:
public double[] askForFourDigits() {
double[] userInput = new double[4];
for (int i = 0; i < userInput.length; i++) {
userInput[i] = /* ask the user for a digit*/;
}
return userInput;
}
You'll add all each of these arrays to one list of arrays:
public static void main(String[] args) {
// We will add all user inputs (repesented as array of size 4) to this list.
List<double[]> allNumbers = new ArrayList<>();
do {
double[] numbers = askForFourDigits();
allNumbers.add(numbers);
displayCurrentCycle(numbers);
displayAll(allNumbers);
} while(/* hey user, do you want to continue */);
}
You can now use the list to compute statistics for numbers entered during all cycles:
public static void displayAll(List<double[]> allNumbers) {
int maximum = 0;
for (double[] numbers : allNumbers) {
for (double number : numbers) {
maximum = Math.max(maximum, number);
}
}
System.out.println("The greatest ever entered number is " + maximum);
}

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.

Categories

Resources