Having problems with arrays (involving user multiple inputs)? - java

int number = keyboard.nextInt();
String [][] myArray = new String[number][1]
for (int i = 0; i < x; i++)
{
System.out.println("Enter food name: ");
myArray[i][0] = keyboard.nextLine();
for (int j = 0; j < 1; j++)
{
System.out.println("Enter the type of this food: ");
myArray[i][j] = keyboard.nextLine();
}
}
Here is my code for what I am about to ask. I want it to print out these outputs when I run this program:
Enter food name:
(where user type his or her input)
Enter the type of this food:
(where user type his or her input)
(My problem is it prints out this instead for the first loop:)
Enter food name:
Enter the type of this food:
(where user type his or her input)
With no way of entering the food item. After the first loop, then the program is back to normal with the output I want, but how do I change the code so that the first loop will take in user input for "enter food name: "?
Thanks in advance.
Edit: sorry for not seeing that question beforehand but that one is not about a for loop so if I enter an empty string before the next input, my loop will not work. Is there any fix to this?
Edit: Got it to work. Thanks everyone.

You might try something like the code below (this allows information to be entered until the user types end .. rather than requiring the user to know how many items they will enter. Also, a method is created to handle the input .. so you can improve, adjust the method easily.
import java.io.ObjectInputStream.GetField;
import java.util.ArrayList;
import java.util.Scanner;
public class Foodarray {
private static String[][] foodInformation;
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner keyboard = new Scanner(System.in);
foodInformation = getFoodInformation(keyboard);
}
private static String[][] getFoodInformation(Scanner inputDevice) {
String[][] result = null;
boolean isStoping = false;
ArrayList<String> holdName = new ArrayList<String>();
ArrayList<String> holdType = new ArrayList<String>();
while (!isStoping) {
System.out.println("Enter food name (or end to exit): ");
String foodName = inputDevice.nextLine().trim();
isStoping = "end".equalsIgnoreCase(foodName);
if (!isStoping) {
System.out.println("Enter food type");
String foodType = inputDevice.nextLine().trim();
holdName.add(foodName);
holdType.add(foodType);
}
}
int foodCount = holdName.size();
if (foodCount>0) {
result = new String[foodCount][foodCount];
for (int i=0; i < foodCount; i++) {
result[i][0] = holdName.get(i);
result[i][1] = holdType.get(i);
}
}
return result;
}
}

Related

Java array linear search always returns "Book is not found"?

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.

Removing a specific element from array through user input

I am a bit new to arrays and I'm wondering how I can ask a user to input which movie they want to remove from the list of available movies and then how to return a new list that bumps each other movie up one spot. I've watched a bunch of videos but I can't figure it out.. :( It will ask me to enter my username, then show me the menu options. But once I press 3, it does not ask me which movie I would like to delete and it does not remove a movie from the array
package practice;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class Practice {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Scanner sc = new Scanner(System.in);
List<String> allowedUsernames = Arrays.asList("John", "Sam", "Lucy", "Arthur", "Trisha");
System.out.println("Welcome to the Java movie rental store! To start, please enter your username!");
String name = "";
do {
if (!name.equals("")) {
System.out.println("Please enter a valid username.");
}
name = input.nextLine();
} while (!allowedUsernames.contains(name));
System.out.println("Hello " +name+ "! Please select from the following menu options!");
getchoices();
}
public static void getchoices() {
Scanner scan = new Scanner(System.in);
String[] optionslist = {
"1) See full list of movies",
"2) Add a movie",
"3) Delete a movie",
"4) Modify a movie",
"5) Exit"
};
for (int i = 0; i < optionslist.length; i++) {
System.out.println(optionslist[i]);
}
int number = scan.nextInt();
System.out.println("You selected: " + optionslist[number-1].substring(3, optionslist[number - 1].length()));
movieList();
}
public static void printNewMovielist() {
// TODO Auto-generated method stub
String[] newList = {
"Shrek",
"Beauty and the Beast",
"Wall-E",
"Cinderella",
"Alice in Wonderland"
};
System.out.println("Movies Available: ");
newMovieList(newList);
newList = deleteMovies(newList);
System.out.println("The updates list of movies available at the rental store: ");
newMovieList(newList);
deleteMovies(newList);
}
public static void movieList() {
ArrayList<String> Movies = new ArrayList<String>();
System.out.println("Movies Available:");
Movies.add("Shrek");
Movies.add("Beauty and the Beast");
Movies.add("Wall-E");
Movies.add("Cinderella");
Movies.add("Alice in Wonderland");
for (int i = 0; i <Movies.size(); i++) {
System.out.println(Movies.get(i));
}
}
public static String[] deleteMovies (String [] newList) {
String[] deleteMovie = new String [newList.length - 1];
for (int i = 0; i < newList.length; i++) {
deleteMovie[i] = newList[i];
}
Scanner sc = new Scanner (System.in);
System.out.println("Which movie would you like to delete?");
return deleteMovie;
}
public static void newMovieList(String [] newList) {
for (int i = 0; i < newList.length; i++) {
System.out.println((i - 1) + " )" + newList[i]);
}
}
public static String[] deleteMovies(String[] newList) {
String[] deleteMovie = new String[newList.length - 1];
for (int i = 0; i < newList.length; i++) {
deleteMovie[i] = newList[i];
}
Scanner sc = new Scanner(System.in);
System.out.println("Which movie would you like to delete?");
return deleteMovie;
}
You can see above that sc is not used. You create the scanner but you don't ask the user for a nextLine()! Contrast this with how you did it with the input scanner. Therefore, your program will exit because it finished (it's not waiting for a nextLine() from the user).
Edit: As K450 pointed out in the comments, you don't even reach this above point in the code. You simply print out which option they select, and then list all movies, and that's all. If your program sees that the user tries to delete a movie (entered that option), you should call this method.
To "remove" an element from an array by shifting everything, you can create an array of length n - 1 similar to what you did, but then note that the index of all elements after the removed element in the original array will be one greater than where it should be copied in the new array.
For example, if you'd like to delete Sam in the array:
["John", "Sam", "Mary"]
Then you would want `
newArray[0] = oldArray[0];
newArray[1] = oldArray[2];
There are ways to do this without using a for loop, but I would suggest at least attempting it as an exercise. A better option would probably be an ArrayList for your use case though, since you can easily remove an element at an index.

Getting multiple Strings into an Array [duplicate]

This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 6 years ago.
I'm having difficulties with my homework. I have the basic logic down but I'm messing up. The objective is to make a receipt from a shopping list that's inputted by the user. For example, the user enters:
Apples
OraNgeS // also it's not case sensitive
Oranges
Bananas
!checkout //this is to indicate the list is over
Output:
Apples x1
Oranges x2
Bananas x1
I'm stuck. My code so far:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.printf("Enter the items you wish to buy:");
String[] input = new String [keyboard.nextLine()];
keyboard.nextLine(); //consuming the <enter> from input above
for (int i = 0; i < input.length; i++) {
input[i] = keyboard.nextLine();
}
System.out.printf("\nYour input:\n");
for (String s : input) {
System.out.println(s);
}
}
I know I'll have to add the if statement eventually so if they type in "!checkout" it'll end the list. but I can't get past this yet.
Any tips or advice?
Try to use ArrayList <-- Link.
Array is need to statically initialize it first before you can use it while ArrayList is automatically expanding when you add values on it. you can use ArrayList without initializing a range on it. Here is the sample:
List<String> fruitList = new ArrayList<>();
Scanner keyboard = null;
Boolean isNotDone = true;
System.out.println("Press 'Q' if you want to print out.");
while(isNotDone) {
keyboard = new Scanner(System.in);
System.out.print("Input Fruits: ");
String temp = keyboard.nextLine();
if(temp.equalsIgnoreCase("q")) {
isNotDone = false;
} else {
fruitList.add(temp);
}
}
System.out.println(fruitList);
The following code will do exactly what you are looking for:
Scanner keyboard = new Scanner(System.in);
List<String> inputItems = new ArrayList<String>();
List<String> printedResults = new ArrayList<String>();
String input = keyboard.nextLine();
while(!"!checkout".equals(input))
{
inputItems.add(input);
input = keyboard.nextLine();
}
for(int i=0; i<inputItems.size();i++)
{
Integer thisItemCount = 0;
String currentItem = inputItems.get(i);
for(int j=0; j<inputItems.size();j++)
{
if(inputItems.get(j).toLowerCase().equals(currentItem.toLowerCase()))
thisItemCount++;
}
if(!printedResults.contains(currentItem.toLowerCase()))
{
System.out.println(currentItem.toLowerCase() + " x" + thisItemCount);
printedResults.add(currentItem.toLowerCase());
}
}

Passing an array to another method and copying it

I am trying to pass an array from one method to another method and then copy the contents of that array into a new array. I am having trouble with the syntax to accomplish that task.
Does anyone have some reference material that I could read about this topic or maybe a helpful tip that I could apply?
I apologize if this is a noob question, but I have only been messing with Java for 3-4 weeks part time.
I know that Java uses pass by value, but what where I'm getting lost is...should I invoke the sourceArray before copying it to the targetArray?
My goal here is not to be just handed an answer, I need to understand WHY.
Thanks...in advance.
package cit130mhmw08_laginess;
import java.util.Scanner;
public class CIT130MHMW08_Laginess
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Please enter the total number of dealers: ");
int numDealers = input.nextInt();
numDealers = numberOfDealers(numDealers);
System.out.printf("%nPlease enter the required data for each of your dealers:");
dataCalculation(numDealers);
}//main
//METHOD 1
public static int numberOfDealers(int dealers)
{
int results;
Scanner input = new Scanner(System.in);
while(dealers < 0 || dealers > 30)
{
System.out.printf("%nEnter a valid number of dealers: ");
dealers = input.nextInt();
}
results = dealers;
return results;
}//number of dealers methods
//METHOD 2
public static void dataCalculation(int data)
{
String[] dealerNames = new String[data];
Scanner input = new Scanner(System.in);
System.out.printf("%nEnter the names of the dealers:%n ");
for(int i = 0; i < data; i++)
{
String names =input.nextLine();
dealerNames[i]= names;
}
int[] dealerSales = new int[data];
System.out.printf("%nEnter their sales totals: %n");
for(int i = 0; i < data; i++)
{
int sales = input.nextInt();
dealerSales[i] = sales;
}
for(int i = 0; i < data; i++)
{
System.out.println(" " + dealerNames[i]);
System.out.println(" " + dealerSales[i]);
}
//gather the required input data.
//Perform the appropriate data validation here.
}//data calculations
//METHOD 3
public static int commission(int data)
{
//Create array
int[] commissionRate = new int[dealerSales];
//Copy dealerSales array into commissionRate
System.arraycopy(dealerSales, 0, commissionRate, 0, dealerSales.length);
//calculate the commission array.
//$1 - $5,000...8%
//$5,001 to $15,000...15%
//$15,001...20%
//
}//commission method
}//class
If you want to copy an array, you can use the Arrays.copyOf(origin, length) method. It takes 2 arguments, first one is the array from which the data is supposed to be copied and second is the length of the new array, and import java.util.Arrays.
-See the link for more info https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#copyOf(int[],%20int)

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