gpt4 book ai didi

java - 解析txt文件

转载 作者:搜寻专家 更新时间:2023-10-31 20:33:44 25 4
gpt4 key购买 nike

我必须编写一个程序来解析棒球运动员的信息以及来自 txt 文件的击球、出局、保送等信息。例如,txt 文件可能如下所示:Sam Slugger,h,h,o,s,w,w,h,w,o,o,o,h,s吉尔詹克斯,o,o,s,h,h,o,o威尔琼斯,o,o,w,h,o,o,o,o,w,o,o

我知道如何解析文件并让代码完美运行。我遇到的唯一问题是我们应该只打印每个玩家和 3 个或他们的游戏的名字。例如:Sam Slugger 命中,命中,出局吉尔詹克斯出去,出去,牺牲飞威尔琼斯出去,出去,走

我不确定如何限制这个,每次我尝试在 3 时将其切断时,我总是让第一个人工作正常,但它打破了循环并且对所有其他玩家没有任何作用。

这是我目前所拥有的:

import java.util.Scanner;
import java.io.*;

public class ReadBaseBall{

public static void main(String args[]) throws IOException{

int count=0;
String playerData;
Scanner fileScan, urlScan;

String fileName = "C:\\Users\\Crust\\Documents\\java\\TeamStats.txt";
fileScan = new Scanner(new File(fileName));

while(fileScan.hasNext()){

playerData = fileScan.nextLine();
fileScan.useDelimiter(",");

//System.out.println("Name: " + playerData);

urlScan = new Scanner(playerData);
urlScan.useDelimiter(",");


for(urlScan.hasNext(); count<4; count++)

System.out.print(" " + urlScan.next() + ",");

System.out.println();

}
}
}

打印出来: Sam Slugger, h, h, o,但随后其他玩家都被淘汰了。我需要帮助才能打印其他的。

最佳答案

在这里,使用 FileReader 试试这个假设你的文件内容格式是这样的

 Sam Slugger,h,h,o,s,w,w,h,w,o,o,o,h,s
Jill Johns,h,h,o,s,w,w,h,w,o,o,o,h,s

如果每个球员都在他/她自己的队伍中,那么这对你有用

 BufferedReader reader;
try {
reader = new BufferedReader(new FileReader(new File("file.txt")));
String line = "";
while ((line = reader.readLine()) != null) {
String[] values_per_line = line.split(",");
System.out.println("Name:" + values_per_line[0] + " "
+ values_per_line[1] + " " + values_per_line[2] + " "
+ values_per_line[3]);
line = reader.readLine();
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}

否则,如果它们像一条线一样排成一行,那将毫无意义,然后修改此示例。

 Sam Slugger,h,h,o,s,w,w,h,w,o,o,o,h,s| John Slugger,h,h,o,s,w,w,h,w,o,o,o,h,s

BufferedReader reader;
try {
reader = new BufferedReader(new FileReader(new File("file.txt")));
String line = "";
while ((line = reader.readLine()) != null) {
// token identifier is a space
String[] data = line.trim().split("|");
for (int i = 0; i < data.length; i++)
System.out.println("Name:" + data[0].split(",")[0] + " "
+ data[1].split(",")[1] + " "
+ data[2].split(",")[2] + " "
+ data[3].split(",")[3]);
line = reader.readLine();
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}

关于java - 解析txt文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29838469/

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