gpt4 book ai didi

java - 如何从文件中读取内容并将其存储在二维数组中

转载 作者:行者123 更新时间:2023-12-02 05:35:37 25 4
gpt4 key购买 nike

我试图从文本文件中读取内容并将它们存储在二维数组中,但是遇到了错误。

这些是文件的内容:

R1 R2 R3 R4 R5

1 J S2 Q S2 J2 J S2 Q S2 J3 J S2 Q S2 J4 J S2 Q S2 J5 J Q S5 Q J6 S3 Q S5 Q S37 S3 Q S5 Q S38 S3 Q S5 Q S39 S3 S1 S5 S1 S310 S1 S5 S1 A11 A S1 K S1 A12 A S1 K S1 A13 A S1 K S1 A14 A S1 K S1 A15 S2又名S216 S2 A S3 A S217 S2 A S3 A S218 S2 A S3 A S219 S2 A S3 A S220 Q S5 S3 S5 Q21 Q S5 J S5 Q22 Q S5 J S5 Q23 Q S5 J S5 Q24 Q S5 J S5 Q25 S4 K S2 K S426 S4 K S2 K S427 S4 K S2 K S428 S4 K S2 K S429 S4 K S2 K S430K S4 S2 S4 K31K S4 A S4 K32K S4 A S4 K33K S4 A S4 K34K S4 A S4 K35 S1 S4 A S4 S136 S1 A S1 A S137 S1 A S1 A S138 S1 A S1 A S139 S1 A S1 A S140 Q S3 S1 S3 Q41 Q S3 Q S3 Q42 Q S3 Q S3 Q43 Q S3 Q S3 Q第44章45 S2 J S4 J S246 S2 J S4 J S247 S2 J S4 J S248 S2 S2 S4 S2 S249 S2 S2 A S2 S250J S2 A S2 J51 J S2 A S2 J第52章第53章第54章55 S5 Q J Q S556 S5 JJ J S557 S5 JJ J S558 S5 J S1 J S559 S5 J S1 J S560 A S3 S1 S3 A61 S3 S1 S3 A62 A S3 Q S3 A63 A S3 Q S3 A第64章65 S1 K Q K S166 S1 K S4 K S167 S1 K S4 K S168 S1 Q S4 Q S169 S1 Q S4 Q S170KQKQK第71章第72章第73章第74章75 S3 JJ J S376 S3 NAJ NA S377 S3 NAJ NA S378 S3 NA J NA S3

我尝试通过将每一行拆分为一个字符串数组来实现此目的,但是我遇到了之前的错误。这是我当前的代码:

package slots;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;

public class Slots {

public static void main(String[] args) throws FileNotFoundException
{
Scanner sc = new Scanner(new BufferedReader(new FileReader("reels_template.txt")));

String [][] arr = new String[78][6];

while(sc.hasNextLine()) {
for (int i=0; i<78; i++) {
String[] line = sc.nextLine().trim().split(" ");
for (int j=0; j<5; j++) {
arr[i][j] = line[j];
}
}
}

for (int i = 0; i < 78; i++) {
for ( int j = 0; j < 6; j++) {
System.out.print(arr[i][j]);
}
System.out.println();
}

}

}

这是错误:

Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1585)
at slots.Slots.main(Slots.java:19)
Java Result: 1

编辑:

根据 Logan Wlv 的评论进行一些更改后,我遇到了以下问题。该代码能够成功读取文件,但是它不会读取每行的最后一个元素。更新代码:

Scanner sc = new Scanner(new BufferedReader(new FileReader("reels_template.txt")));

String [][] arr = new String[78][6];
String[] line = {};


for (int i=0; i<78; i++) {
if (sc.hasNextLine()) {
line = sc.nextLine().trim().split("\\s+");
}
for (int j=0; j<5; j++) {
arr[i][j] = line[j] + " ";
}
}

示例输出:

# R1 R2 R3 R4 null
1 J S2 Q S2 null
2 J S2 Q S2 null
3 J S2 Q S2 null

最佳答案

sc.hasNextLine() 的检查位置错误,请尝试以下方法。同时删除 while 循环。

    for (int i=0; i<78; i++) {
if(sc.hasNextLine()) {
String[] line = sc.nextLine().trim().split(" ");
for (int j=0; j<5; j++) {
arr[i][j] = line[j];
}
} else {
break;
}
}

关于java - 如何从文件中读取内容并将其存储在二维数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56169057/

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