gpt4 book ai didi

java - 使用 .split() 方法并仅获取创建回的字符串数组的一部分

转载 作者:行者123 更新时间:2023-11-29 05:33:11 25 4
gpt4 key购买 nike

我需要从这样的 .dat 文件中读取文本:

4
Mary 13.99
Ruth 22.04
Anne 12.39
Talor 18.34

我使用了一个缓冲阅读器,看起来像这样:

public class Tester{

public static void main(String [] args){

BufferedReader reader = null;

try {
File file = new File("C:\\Users\\hoguetm\\workspace\\practiceproblems\\beautiful.dat");
reader = new BufferedReader(new FileReader(file));

String line;

while ((line = reader.readLine()) != null) {
//System.out.println(line);
//split will go here
String[] str1Array = line.split(" ");
System.out.println(str1Array[0]);

//works

/*
for (String retval: line.split(" ")){
System.out.println(retval);
}
*/
}

} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

我需要在除 4 以外的行末尾添加数字并打印出总和,但是当我将 [0] 更改为 [1] 时,它显示超出范围。请帮忙

最佳答案

不要拆分第一行。继续拆分第二行。

reader.readLine(); //added this line

while ((line = reader.readLine()) != null){

}

关于java - 使用 .split() 方法并仅获取创建回的字符串数组的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20404449/

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