从用户输入获取文件并将整数存储到数组中

时间:2020-09-17 01:03:46

标签: java arrays file methods return

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

在一行中采样文件内容:

34 a 55 18 47 89 b 45 67 59 abbbb 88 37 20 27 10 78 39 21 n m 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();
     }
}

1 个答案:

答案 0 :(得分:2)

在您的情况下,我不会使用Scanner对象获取int值,因为当您使用扫描仪时,当您拥有EOF(文件末尾)时,您只会为false获得hasNext()字符。 因此,一旦您检索了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;
相关问题