【问题标题】:Getting a file from user input and store integers into array从用户输入中获取文件并将整数存储到数组中
【发布时间】:2021-01-03 20:44:39
【问题描述】:

我正在尝试从 java 中的用户输入打开一个文件,然后读取该文件并仅获取每行中的整数,然后将其放入一个数组并返回该数组。我更熟悉python在文件中抓取项目而不是java。

一行文件的示例内容:

34 a 55 18 47 89 b 45 67 59 abbbb 88 37 20 27 10 78 39 21 nm ghff

我的代码:

private static int[] getArray(){
    List<Integer> temp = new ArrayList<Integer>();
    System.out.print("Please input the name of the file to be opened: ");
    try{
        String filename = in.next();
        File file = new File(filename);
        Scanner inputFile = new Scanner(file);
        while (inputFile.hasNextInt()){
            temp.add(inputFile.nextInt());
        }
    } catch (FileNotFoundException e){
        System.out.println("---File Not Found! Exit program!---");
        System.exit(0);
    }
    int[] array = new int[temp.size()];
    for (int i = 0; i < array.length; i++){
        array[i] = temp.get(i);
    }
    return array;
}

编辑:

我发现我的 while 循环是错误的。应该是这样的:

while (inputFile.hasNext()){
     if (inputFile.hasNextInt()){
        temp.add(inputFile.nextInt());
     }
     else{
        inputFile.next();
     }
}

【问题讨论】:

标签: java arrays file methods return


【解决方案1】:

在您的情况下,我不会使用 Scanner 对象来获取 int 值,因为当您使用扫描仪时,当您有 EOF(文件结尾)字符时,您只会为 hasNext() 获得 false。 因此,一旦您检索到 filename,请使用下面的代码,这将消除给定字符串中的所有字符并将其替换为单个 whitespace

String stringWithSingleWS = filename.trim().replaceAll("([a-zA-Z])"," ").replaceAll("\\s{2,}"," ");

然后你可以把它解析成数组,直接返回结果,甚至不用转换成List对象变量。

    int[] values = java.util.Arrays.stream(stringWithSingleWS.split(" "))
                    .mapToInt(Integer::parseInt)
                    .toArray();
return values;

【讨论】:

  • 我试过这样做,但仍然返回 0。这与我的 while 循环实际上没有获取整数值有关吗?
  • 这不适用于测试用例34 a 55 18 47 89 b 45 67 59 abbbb 88 37 20 27 10 78 39 21 n m ghff
  • 查看答案,我根据您的情况进行了改进。
猜你喜欢
  • 2011-11-05
  • 1970-01-01
  • 2018-01-19
  • 2015-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-22
  • 1970-01-01
相关资源
最近更新 更多