gpt4 book ai didi

java - 如何读取以逗号分隔的文件

转载 作者:行者123 更新时间:2023-11-30 03:20:14 25 4
gpt4 key购买 nike

我试图从包含字符串列表的文件中读取内容。文件中有三行,我尝试按照文件中的外观打印它们,但输出仅打印第一行。不应打印“女人”。也不应该是“人”

   public void readFile(String fileName) {
String gender;
String width;
String height;
String name;
String x;
String y;

try {
scanIn = new Scanner (new File (fileName));
this.scanIn.useDelimiter(", ");

} catch (FileNotFoundException | NumberFormatException exception) {

exception.getMessage();
}

while(this.scanIn.hasNext()){
gender = scanIn.next();

if(gender.equals("woman")){

width = scanIn.next();
height = scanIn.next();
x = scanIn.next();
y = scanIn.next();
name = scanIn.next();

System.out.printf("%s %s %s %s %s", width,height,x,y,name);
}
if(gender.equals("man")){

width = scanIn.next();
height = scanIn.next();
x = scanIn.next();
y = scanIn.next();
name = scanIn.next();

System.out.printf("%s %s %s %s %s", width,height,x,y,name);

}
}
}

文件看起来像

man, 20, 15, 55, 90, phil
woman, 30, 10, 5, 80, Sam
man, 320, 170, 10, 90, olie

输出应该是

20, 15, 55, 90, phil
30, 10, 5, 80, Sam
320, 170, 10, 90, olie

相反,输出给了我

20, 15, 55, 90, phil
woman

最佳答案

该错误是因为当您使用分隔符", "时,扫描器在遇到新行时不会停止。

因此,当它读取第一行时,它将读取 phil\nwomen 作为单个标记。所以你的循环会变得困惑。

要修复,您可以告诉它在 ", |\n" 上进行分隔,这也会在新行字符上进行分隔。

scanIn.useDelimiter(", |\n");

注意:您可能还需要在 printf() 语句末尾添加一个换行符,否则您将得到整个在一行中输出。

关于java - 如何读取以逗号分隔的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31488366/

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