从用户输入获取文件,并将整数存入数组。

huangapple go评论75阅读模式
英文:

Getting a file from user input and store integers into array

问题

以下是您提供的代码翻译后的内容:

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

文件的示例内容一行):

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("请输入要打开的文件名:");
    try{
        String filename = in.next();
        File file = new File(filename);
        Scanner inputFile = new Scanner(file);
        while (inputFile.hasNext()){
            if (inputFile.hasNextInt()){
                temp.add(inputFile.nextInt());
            }
            else{
                inputFile.next();
            }
        }
    } catch (FileNotFoundException e){
        System.out.println("---文件未找到!退出程序!---");
        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();
     }
}
英文:

I am trying to open a file from user input in java and then read that file and grab only the integers in each line then place it into an array and return the array. I'm more familiar with python in grabbing items in a file than java.

Sample contents of the file in one line:

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

My code:

private static int[] getArray(){
List&lt;Integer&gt; temp = new ArrayList&lt;Integer&gt;();
System.out.print(&quot;Please input the name of the file to be opened: &quot;);
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(&quot;---File Not Found! Exit program!---&quot;);
System.exit(0);
}
int[] array = new int[temp.size()];
for (int i = 0; i &lt; array.length; i++){
array[i] = temp.get(i);
}
return array;
}

Edit:

I figured it out my while loop was wrong. It should be like this:

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

答案1

得分: 2

在您的情况下我不会使用Scanner对象来获取int值因为当您使用scanner时只有在存在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;
英文:

In your case, I wouldn't use Scanner object to get the int values, because when you use scanner, you only get false for hasNext() when you have a EOF(end of file) character.
So once you retrieve the filename use the code below, which will eliminate all of the characters from given string and replace it with a single whitespace

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

Then you can parse it into array and directly return the result without even casting into a List object variable.

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

huangapple
  • 本文由 发表于 2020年9月17日 09:03:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/63929857.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定