【问题标题】:Taking different inputs from a file and distinguishing them从文件中获取不同的输入并区分它们
【发布时间】:2022-01-23 22:04:23
【问题描述】:

所以我有一个文本文件(不是双倍行距)

4
1 5 3 5 6 7 9
14
0 3 1 6 3
11

我想将这些数字作为测试用例值(仅限第一个数字)、排序状态(可以是 0/1)、数组中的元素数以及数组元素本身。然后我使用更多具有相同信息的测试数组。但是,使用我的代码,我无法弄清楚如何将数字添加到数组中。

    File file = new File("\\Users\\rike6\\OneDrive\\Desktop\\sample_in.txt");
    @SuppressWarnings("resource")
    Scanner scan = new Scanner(file);
    
    int[] array = {};
    
    int testCase = scan.nextInt();
    int sortStatus = scan.nextInt();
    int arraySize = scan.nextInt();
    for (int i = 0; i < arraySize - 1; i++)
        array[i] = scan.nextInt();
    int target = scan.nextInt();

输出: 测试用例数量:4

此数组是否已排序(1 表示是,0 表示否):是

此数组中的元素数:5

数组元素:{ 3,5,6,7,9}

目标:14

下一个数组是否已排序:否

等等……

【问题讨论】:

  • 您需要调整数组的大小。例如int[] array = new int[arraySize]。更好的是,使用ArrayList
  • 排序状态是什么意思?您已经显示了输入。请显示该输入的预期输出。
  • 我添加了一个输出。我只想将文件中的输入分配给程序中的变量。

标签: java arrays java.util.scanner filereader


【解决方案1】:

这是您在数组中读取的方式。在这种情况下,数据位于您发布的一串值中(除了 11 后面没有任何后续数据)。读取字符串就像读取文件一样。

String data = "4 1 5 3 5 6 7 9 14 0 3 1 6 3";
Scanner scan = new Scanner(data);

while (scan.hasNext()) {
    int testCase = scan.nextInt();
    int sortStatus = scan.nextInt();
    int arraySize = scan.nextInt();
    int[] arr = new int[arraySize];
    for (int i = 0; i < arraySize; i++) {
        arr[i] = scan.nextInt();
    }
    
    System.out.printf("testCase = %d, sortStatus = %d, arraysSize = %d, array=%s%n",
            testCase, sortStatus, arraySize, Arrays.toString(arr));
}

打印

testCase = 4, sortStatus = 1, arraysSize = 5, array=[3, 5, 6, 7, 9]
testCase = 14, sortStatus = 0, arraysSize = 3, array=[1, 6, 3]

【讨论】:

  • 我希望能对此提供一些反馈。
猜你喜欢
  • 2014-03-20
  • 1970-01-01
  • 1970-01-01
  • 2016-08-18
  • 2015-04-09
  • 2019-04-27
  • 2020-09-02
  • 2023-04-04
  • 2017-04-27
相关资源
最近更新 更多