1
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.

1 Answers1

0

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;

}

 }
ErstwhileIII
  • 4,691
  • 2
  • 21
  • 36