这是我目前用于从文本文件中检索数据的程序,如下所示:
try {
File file = new File("dataCollection.txt");
Scanner s = new Scanner(file);
while(s.hasNext()){
String firstName = s.next();
String lastName = s.next();
String address = s.next();
String suiteNumber = s.next();
String city = s.next();
String state = s.next();
String zipCode = s.next();
String balance = s.next();
System.out.println("First Name is " + firstName);
}
s.close();
输入文件如下所示:
FirstNameFXO|LastFXO|2510 Main Street|Suite 101D|City100|GA|72249|$280.80
FirstNamePNR|LastPNR|396 Main Street|Suite 100A|City102|GA|24501|$346.01
FirstNameXZU|LastXZU|2585 Main Street|Suite 107C|City101|GA|21285|$859.40
我正在尝试打印出firstName,以便稍后可以将这些值用于各种其他用途,但它会输出它(输出更大,这只是前三行):
First Name is FirstNameFXO|LastFXO|2510
First Name is FirstNameXZU|LastXZU|2585
First Name is FirstNameGHP|LastGHP|2097
答案 0 :(得分:0)
您正在使用具有默认分隔符.next()
的方法whitespace
的问题,因此它将读取并返回下一系列字符串标记,直到到达空格。
在你的情况下它会返回:
firstname ="FirstNameFXO|LastFXO|2510";
要解决您的问题,您可以使用方法.nextLine()
读取每一行,然后将其保存在变量line
中并将其子串以获得名字:
while(s.hasNextLine()){
String line = s.nextLine();
String firstname = line.substring(0,line.indexOf("|"));
System.out.println("First Name is " + firstName);
}