【问题标题】:Storing the input in 3 dimentional arrays将输入存储在 3 维数组中
【发布时间】:2015-12-05 01:51:59
【问题描述】:

我想为想要用我的 java 程序测试的不同测试用例存储输入。 在示例输入下方:

1
4 5
2 5 6 8
3 8 5 1 7

这里:

  • 第一行 - 测试用例数。
  • 数组 M 和 N 的第二行长度。
  • M 数组的第 3 行元素。
  • 第4行:N个数组的元素。

我的问题,如何在运行时存储所有这些元素并将它们作为我的 java 类的输入。

【问题讨论】:

  • 这里是输入以获得更好的视图:1 4 5 2 5 6 8 3 8 5 1 7
  • 您是如何获得样本输入的?显示您的代码!
  • 请向我们展示您为解决问题而编写的代码。提示:我们不是来帮你编程的……
  • @StephenC,分享下面的代码,

标签: java arrays input


【解决方案1】:
/*
     * Sharing the code here with . Yes,there will be multiple test cases in
     * the input Suggest any better way if you find
     */
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    int testcases = Integer.parseInt(br.readLine());
    String readinput = "";
    int count = 0;
    int[][][] array = new int[testcases][3][];
    for (int i = 0; i <= array.length; i++) {
        readinput = "";
        count = 0;
        for (int j = 0; j < array[i].length; j++) {
            readinput = br.readLine();
            count = readinput.split(" ").length;
            String[] data = new String[count];
            data = readinput.split(" ");
            System.out.println(Arrays.toString(data));
            for (int k = 0; k < count; k++) {

                array[i][j][k] = Integer.parseInt(data[k]);
            }

        }

    }

【讨论】:

    【解决方案2】:

    正如@Vamsi krishna 建议的那样,输入的单独行并不真正相关。因此,您可以将这些值作为参数输入到 java 命令行并在 main 方法中读取它们:

    public static void main(String[] args) {
        int i = 0;
        int numberOfTests = Integer.parseInt(args[i++]);
        int mSize = Integer.parseInt(args[i++]);
        int nSize = Integer.parseInt(args[i++]);
        int[] mValues = new int[mSize];
        for(n = 0; n < mSize; n++) {
            mValues[n] = Integer.parseInt(args[i++]);
        }
        int[] nValues = new int[nSize];
        for(n = 0; n < mSize; n++) {
            nValues[n] = Integer.parseInt(args[i++]);
        }
    }
    

    然后调用您的应用程序:

    java MyApp.class 1 4 5 2 5 6 8 3 8 5 1 7
    

    注意:您没有说明应该如何使用测试用例的数量。如果这意味着可以将多组 m,n 数组指定为输入,则需要进行额外的迭代,并且 m,n 数组必须存储在某个地方,例如另一个数组中。

    如果这种简单的方法不够好(由于输入缺少格式,它可能太容易出错),您可以将输入放在一个文件中并使用 java.util.Scanner 读取它:

    public static void main(String[] args) {
        File file = new File(args[0]);
        Scanner sc = new Scanner(file);
        try {
            while (sc.hasNextInt()) {
                int i = sc.nextInt();
                // see logic above but use sc.nextInt() to get the next int     value
            }
        }
        finally {
            sc.close();
        }
     }
    

    调用它:

    java MyApp.class C:\input.txt
    

    并将输入放入文件 C:\input.txt。

    【讨论】:

      猜你喜欢
      • 2014-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多