有阵列问题(涉及用户多个输入)?

时间:2014-04-06 14:50:32

标签: java arrays user-input

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();
    }
}

这是我要问的问题的代码。我想在运行这个程序时打印出这些输出:

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)

无法进入食品。在第一个循环之后,程序恢复到我想要的输出正常,但是如何更改代码以便第一个循环将输入“输入食物名称:”的用户输入?

提前致谢。

编辑:抱歉没有事先看到这个问题,但是那个问题不是for循环所以如果我在下一个输入之前输入一个空字符串,我的循环将无效。有没有解决这个问题?

编辑:让它发挥作用。谢谢大家。

1 个答案:

答案 0 :(得分:0)

您可以尝试类似下面的代码(这允许输入信息,直到用户输入结束...而不是要求用户知道他们将输入多少项。此外,创建一个方法来处理输入。所以你可以轻松改进,调整方法。

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;

}

 }