【问题标题】:Having problems with arrays (involving user multiple inputs)?数组有问题(涉及用户多个输入)?
【发布时间】:2014-04-06 14:50:31
【问题描述】:
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 循环无关,所以如果我在下一个输入之前输入一个空字符串,我的循环将无法工作。有什么解决办法吗?

编辑:让它工作。谢谢大家。

【问题讨论】:

  • 抱歉没有早点看到。有没有解决循环的方法?和那个问题的答案一样吗?
  • 只需在int number = keyboard.nextInt(); 行后面写上keyboard.nextLine(); 即可。
  • 好的,我会试试的。谢谢
  • 再次感谢 Aman Agnihotri。它确实有效xD。如果你愿意,你可以把它作为这个问题的答案,我会选择它作为最好的。

标签: java arrays user-input


【解决方案1】:

您可以尝试类似下面的代码(这允许在用户键入 end 之前输入信息 .. 而不是要求用户知道他们将输入多少项。此外,还创建了一个方法来处理输入。 . 这样您就可以轻松改进、调整方法。

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;

}

 }

【讨论】:

  • 感谢您的意见。我一定会检查出来的。
猜你喜欢
  • 2022-01-12
  • 2014-05-29
  • 2021-08-05
  • 2014-09-21
  • 2020-04-14
  • 1970-01-01
  • 1970-01-01
  • 2023-03-05
  • 2020-10-22
相关资源
最近更新 更多