gpt4 book ai didi

java - 数组/循环不输出主行

转载 作者:行者123 更新时间:2023-12-01 10:32:52 25 4
gpt4 key购买 nike

我的代码有一个小问题,我不太确定如何修复它。基本上我试图将文件分成不同的行(帧),然后将这些行输入到文件中,并继续打印它们。我的文件第一行永远不会打印。

public class Main {
public static void main(String[] args) throws IOException
{
/*Switch switcherino = new Switch();*/
Frame frame = new Frame();

Scanner input = new Scanner(System.in);
System.out.println("Enter the name of the file to process: ");
String fileName = input.nextLine();

FileInputStream inputStream =
new FileInputStream(fileName);
InputStreamReader inputStreamReader =
new InputStreamReader(inputStream,Charset.forName("UTF-8"));
BufferedReader bufferedReader =
new BufferedReader(inputStreamReader);

try{
String str = " ";

while((str = bufferedReader.readLine())!= null){
String words[] = str.split(" ");

for (int i = 0; i < words.length; i++){
words[i] = bufferedReader.readLine();
System.out.println(words[i]);
}
}
}
catch (IOException e){
e.printStackTrace();
} finally {
try {
if (inputStream != null)
inputStream.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}

我不想使用 ArrayList,因为它可能会更容易。

提前致谢!

文件:(switch.txt)

fa00 123123123abc 111111222222 data1
fa01 111111222222 123123123abc data2
fa03 444444444444 123123123abc data3
fa01 123123123abc 4353434234ab data4
fa99 a11b22c33d44 444444444444 data5

输出:(来自 System.println(words[i]);)

fa01 111111222222 123123123abc data2
fa03 444444444444 123123123abc data3
fa01 123123123abc 4353434234ab data4
fa99 a11b22c33d44 444444444444 data5

最佳答案

这是错误的逻辑:您阅读了该行,将其拆分为单词,然后继续打印它们 - 无需尝试阅读更多行

    while((str = bufferedReader.readLine())!= null){
String words[] = str.split(" ");

for (int i = 0; i < words.length; i++){
words[i] = bufferedReader.readLine();
System.out.println(words[i]);
}
}

用这个代替

    while((str = bufferedReader.readLine())!= null){
String words[] = str.split(" ");

for (int i = 0; i < words.length; i++){
System.out.println(words[i]);
}
}

关于java - 数组/循环不输出主行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35000392/

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