gpt4 book ai didi

java - 如何将多行单词转换为单个数组

转载 作者:行者123 更新时间:2023-12-01 09:06:27 24 4
gpt4 key购买 nike

例如,我想转动这个列表:

dog cat

trees breeze

...

它有一定数量的行,每个行有两个单词到一个数组中。

如何使用 BufferedReader 执行此操作?问题是我不知道如何在没有 for 循环或其他东西的情况下继续解析 x 次。我该如何使用 for 循环来做到这一点?

这里是示例代码:

BufferedReader br = new BufferedReader(new FileReader("input.in"));
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("input.out")));
static int[] words
for (int i=1; i<2N; i+2) {
StringTokenizer i
words[i] = String.parsestring}
}
}

最佳答案

如果您在使用 BufferedReader 逐行浏览时遇到问题,您可以使用 Scanner 代替,并假设文件不是很大,将整个文件扫描到一个字符串,然后使用 split()获取文件中所有单词的数组:

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;

public class ArrayFromFile{
public static void main(String []args){
try (Scanner scanner = new Scanner(new File("data.txt"))) {
String text = scanner.useDelimiter("\\A").next(); //Get contents of file as String
String[] words = text.split(" ");

for(String word : words) //Printing out the elements in the array
System.out.println(word);

} catch (FileNotFoundException e){
e.printStackTrace();
}
}
}

关于java - 如何将多行单词转换为单个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41233413/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com