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.
Related
When I insert the arguments the search always returns "not found" - even though the searched value was input into the array?
import java.util.Scanner;
public class assignment {
public static void main (String[] args)
{
Scanner sc = new Scanner(System.in);
String searchValue = "";
String [] BookID = new String [3];
String [] Booktitle = new String [3];
//input the BookID
System.out.println("Enter the 12 BookID");
for (int a = 0 ; a < BookID.length; a++)
{
System.out.print("BookID :");
BookID[a] = sc.next();
}
//Input the book title
for (int b = 0 ; b < Booktitle.length ; b++)
{
System.out.print("Booktitle :");
Booktitle[b] = sc.next();
}
//The Linear search on BookID
System.out.print("Enter BookID to find :");
for(int c = 0; c < BookID.length; c++)
{
searchValue = sc.next();
if(searchValue.equals(BookID))
System.out.print("BookID is found : ");
else
System.out.print("BookID is not found : ");
}
}
}
I'm expecting the result to return like so: if input BookID 112. The Linear search would return "The BookID is found :" instead of the else statement.
Try printing out the value of the bookId you wanna find to see if there anything with the string that could cause it to not be equals. Also, you could convert the string to an integer with:
Integer.parseInt("BookId");
The equals would have less chance of failing, you could also change de the array for an array of int instead of String.
This code has some basic things right, but it could be a bit better. Some of the changes I made are for keeping Java conventions (so the code is easier to read and understand) and some are functional. I added them as comments.
import java.util.Scanner;
public class Assignment {
public static void main (String[] args)
{
Scanner sc = new Scanner(System.in);
String searchValue = "";
String [] bookIDs = new String [3]; //lowercase for the attribute name (convention)
String [] bookTitles = new String [3]; //plural for the array (convention)
//input the BookID
System.out.println("Enter the Book ID");
for (int i = 0 ; i < bookIDs.length; i++) { //you can re-use the i in all loops
System.out.print("Enter " + i + " Book ID: ");
bookIDs[i] = sc.next();
}
//Input the book title
for (int i = 0 ; i < bookTitles.length ; i++) {
System.out.print("Enter " + i + " Book title: ");
bookTitles[i] = sc.next();
}
//The Linear search on BookID
System.out.print("Enter Book ID to find: ");
searchValue = sc.next(); //NOTE: this is your first mistake. read out of the loop
for(int i = 0; i < bookIDs.length; i++) {
if(searchValue.equals(bookIDs[i])) { //NOTE: this is your second mistake - you wanted the array value, not the array
System.out.println("BookID is found in position "+i);
break; //suggestion - stop the loop when found.
}
else {
System.out.println("BookID is not found in position "+i);
}
}
sc.close(); //NOTE: important to close scanners at the end.
}
}
Good luck with your studies.
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
I am new to programming and I decided to learn Java. I had just finished reading about one dimensional array and I am having trouble with searching.
The summary of this program I had made is to ask the user how many students will be enrolled in the class. The user then inputs the name of the students based on the length of the array. Then I want the to be able to have the user search for the students name. How can i accomplish this? What I want to accomplish is when the user inputs the first name it will return the list of full names that has the matching first name. I really struggling with this. Please don't give any advanced methods. I would like to stay in pace pace with my book.
I am using introduction to java programming comprehensive version 10th edition.
import java.util.Scanner;
public class classSystem {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Weclome instructure to your Class System!");
System.out.println("Follow each steps to turn in your work instructor.");
System.out.println("\n1.) Enroll Students:");
System.out.print("\nHow many students are enrolled? ");
int studentAmount = input.nextInt();
String[] enrolledStudents = getStudentAttendance(studentAmount);
System.out.println("Here is your attendance list:");
for (int count = 0; count < enrolledStudents.length; count++) {
System.out.print("\n\t" + (count + 1) + ".) " + enrolledStudents[count]);
}
System.out.print("\n\nWhat sudent do you want to search: ");
String studentSearch = input.nextLine();
System.out.println(getStudent(enrolledStudents, studentSearch));
}
public static String[] getStudentAttendance(int studentAmount)
{
Scanner input = new Scanner(System.in);
String[] enrolledStudents = new String[studentAmount];
System.out.println("Input the students names:");
for (int count = 0; count < enrolledStudents.length; count++)
{
System.out.print((count + 1) + ".) ");
enrolledStudents[count] = input.nextLine();
}
return enrolledStudents;
}
public static String getStudent(String[] enrolledStudents, String StudentSearch)
{
for (int count = 0; count < enrolledStudents.length; count++)
{
if(StudentSearch.equals(enrolledStudents[count]))
{
return getStudent;
}
}
}
}
I have updated your code. Please see the comments inline. Hope this helps.
import java.util.Scanner;
class classSystem {
static Scanner input; //created a static reference for Scanner
//as you will be using in both the methods
public static void main(String[] args) {
input = new Scanner(System.in); //creating the Scanner object.
System.out.println("Weclome instructure to your Class System!");
System.out.println("Follow each steps to turn in your work instructor.");
System.out.println("\n1.) Enroll Students:");
System.out.print("\nHow many students are enrolled? ");
int studentAmount = input.nextInt();
input.nextLine(); //added this to consume new-line leftover
String[] enrolledStudents = getStudentAttendance(studentAmount);
System.out.println("Here is your attendance list:");
for (int count = 0; count < enrolledStudents.length; count++) {
System.out.print("\n\t" + (count + 1) + ".) " + enrolledStudents[count]);
}
System.out.print("\n\nWhat sudent do you want to search: ");
String studentSearch = input.nextLine();
System.out.println(getStudent(enrolledStudents, studentSearch));
input.close(); //close the scanner
}
public static String[] getStudentAttendance(int studentAmount) {
String[] enrolledStudents = new String[studentAmount];
System.out.println("Input the students names:");
for (int count = 0; count < enrolledStudents.length; count++) {
System.out.print((count + 1) + ".) ");
enrolledStudents[count] = input.nextLine();
}
return enrolledStudents;
}
public static String getStudent(String[] enrolledStudents, String studentSearch) {
boolean flag = false; //added flag, this will be true if name is found
//otherwise false
for (int count = 0; count < enrolledStudents.length; count++) {
if (studentSearch.equals(enrolledStudents[count])) {
flag = true;
break; //if name is found breaking the loop.
} else {
flag = false;
}
}
if (flag == true) //checking the flag here
return studentSearch + " is present in the class";
else
return studentSearch + " is not present in the class: ";
}
}
I am getting below result after running my code.
Looks like you already got the idea how to search using .equals() method. Assuming you'll fix getStudent() method by handling "not found" situation, you should be done.
Next, do you want to improve your search, is that your real question? That depends on what type of search do you want to implement. Partial name match, name starts with, ignoring upper/lower case, wildcard search are different options. If that is what you want, please add it to the question.
I'm trying to make a basic program that allows the use to input and remove up to 10 contacts (a [10][4] array supposed to be filled with First Name, Last Name, Phone #, and age). However when I try to input the 5th contact eclipse gives me an error message. I'd like to know why I'm receiving an error message. (I assume it's something to do with the columns since it's whenever i'm inputting something >4, but i'm not sure what exactly.)
import java.util.Scanner;
public class Lab2 {
public static void main(String[] args){
new Lab2 ();
}
// This will act as our program switchboard
public Lab2 (){
Scanner input = new Scanner(System.in);
String[][] personalInfo = new String[10][4];
System.out.println("Welcome to the contacts database.");
System.out.println("Please select a number from the options below");
System.out.println("");
while(true){
// Give the user a list of their options
System.out.println("1: Add a new contact.");
System.out.println("2: Remove an existing contact.");
System.out.println("0: Exit the database.");
// Get the user input
int userChoice = input.nextInt();
switch(userChoice){
case 1:
addContact(personalInfo);
break;
case 2:
removeContact(personalInfo);
break;
case 0:
System.out.println("Thank you for using the contact database.");
System.exit(0);
}
}
}
private void addContact(String personalInfo[][])
{
Scanner input = new Scanner(System.in);
System.out.println();
System.out.println( " Hello user, please enter your contact info. (I.E. First and Last Names, Phone #, and Age. Max 10 Contacts)");
String addedContact = input.nextLine();
int j;
for(int i = 0; i < personalInfo.length; i++)
{
for(j = 0; j < personalInfo.length; j++){
if(personalInfo[i][j] == null)
{
personalInfo[i][j] = addedContact;
break;
}
}
}
}
private void removeContact(String personalInfo[][]) {
Scanner input = new Scanner(System.in);
System.out.print( " Please enter an existing contact that you would like to remove. ");
String deleteContact = input.nextLine();
int i , j;
for(i = 0; i < personalInfo.length; i++)
{
for(j = 0; j < personalInfo.length; j++){
if(personalInfo[i][j].equals(deleteContact))
{
personalInfo[i][j] = null;
break;
}
}
}
}
}
Try like this for(j = 0; j < personalInfo[i].length; j++){
First things first:
String[][] personalInfo = new String[10][4];
This statement creates a 2dimensional array of Strings, thus creating an array that is capable of holding an array that is capable of holding strings. (in this case 10 arrays that keep 4 strings each)
Now the error:
String addedContact = input.nextLine();
This line puts the entire line you added in a single string.
Now the loops:
1. The outer loop loops correctly through the 10 arrays of strings.
2. The inner loop does not loop through the '2nd dimension', that is the actual array which will hold your contact. This loop should be as #Kannan Thangadurai described:
for(j = 0; j < personalInfo[i].length; j++){
(add relevant code here)
}
The last error you made is more of a bug, and is in the way you read out the user input. You actually only ever put a string in the first array and so your four contacts that you saved will all be under personalinfo[1] then you try to add another contact in the fifth place of the array that does not exist, thus raising your error.
You're working with jagged array (or array of arrays)
String[][] personalInfo = new String[10][4];
so in order to itterate it you should use different lengths for dimensions (in general case the
required length is personalInfo[i].length):
for (int i = 0; i < personalInfo.length; ++i) // <- outer array
for (int j = 0; j < personalInfo[i].length; ++j) // <- inner length depends on i
if (personalInfo[i][j] == null) {
personalInfo[i][j] = addedContact;
break;
}
I am trying to use a menu system that can delete a customer from my array myHotel[], this is built from an object.
if(menu.charAt(0) == 'D')deleteCustomer(myHotel[]);
...
public void deleteCustomer(String myHotel[]){
Scanner input = new Scanner(System.in);
System.out.println("Please Enter Room Number to Delete Customer");
roomNum=input.nextInt();
myHotel[roomNum].setName("e");
}
I get the errors, cannot find symbol?
Here is the Full Code
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int roomNum=0;
Room[] myHotel = new Room[10];
for (int x =0; x<10; x++){
myHotel[x] = new Room();
}
String roomName;
String menu;
do {
System.out.println("Please Select an Option from the Menu:");
System.out.println("Enter V to View all Rooms");
System.out.println("Enter A to Add Customer to Room");
System.out.println("Enter D to Delete Customer from Room");
System.out.println("Enter Q to Quit");
menu=input.next();
//if(menu.charAt(0) == 'V')viewAllRooms();
//if(menu.charAt(0) == 'A')addCustomer();
if(menu.charAt(0) == 'D')deleteCustomer(myHotel[]);
} while (menu.charAt(0) != 'Q');
while (roomNum < 10) {
for (int x = 0; x < 10; x++ )
if (myHotel[x].getName().equals("e"))System.out.println("room " + x + " is empty");
System.out.println("Enter room number (0-9) or 10 to stop:");
roomNum = input.nextInt();
System.out.println("Enter name for room " + roomNum + " :");
roomName = input.next();
myHotel[roomNum].setName(roomName);
for (int x = 0; x < 10; x++) {
//System.out.println("room " + x + " occupied by " + myHotel[x].mainName);
System.out.println("room " + x + " occupied by " + myHotel[x].getName());
}
}
}
public void deleteCustomer(String myHotelRef){
Scanner input = new Scanner(System.in);
System.out.println("Please Enter Room Number to Delete Customer");
int deleteRoom=input.nextInt();
myHotelRef[deleteRoom].setName("e");
}
}
You get multiple errors. What is myHotel[]? roomNum is not defined, etc.
Please use your compiler.
Also: please read https://stackoverflow.com/help/how-to-ask :-)
First you need declare myHotel array and pass it with out [].
deleteCustomer(myHotel);
Second, there is not such a method setName(String name) in String class
myHotel[roomNum].setName("e");// no such a method
Third, you need to declare the roomNum variable like:
int roomNum = input.nextInt();
Your main problem is that you've included [] in your call to deleteCustomer. It should be:
if (menu.charAt(0) == 'D') {
deleteCustomer(myHotel);
}
When you reference an array object as a whole you don't include square brackets. Square brackets are for the declaration, initialisation and for accessing individual elements within the array.
I'd also recommend that you get into the habit of always using curly braces with your if, for and while constructs, as not including them is often the cause of bugs. It also makes it easier to read when you come back to it, and you're clearly indicating to others what should be part of the loop and what shouldn't.