尝试存储来自文本文件的值,但输出不正确 [英] Trying to store values from a a text file but it outputting incorrectly
问题描述
try {
File file = new File(dataCollection.txt);
扫描仪s =新扫描仪(文件); (s.hasNext()){
String firstName = s.next();
while(s.hasNext())
String lastName = s.next();
String address = s.next();
字符串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大街|套房101D | City100 | GA | 72249 | $ 280.80
名字PNN | LastPNR | 396大街|套房100A | City102 | GA | 24501 | $ 346.01
FirstNameXZU | LastXZU | 2585 Main Street | Suite 107C | City101 | GA | 21285 | $ 859.40
我试图打印出firstName,所以我可以稍后使用它的各种其他用途,但它会输出这个(输出是更大,这只是前三行):
名字是FirstNameFXO | LastFXO | 2510
名字是FirstNameXZU | LastXZU | 2585
名字是FirstNameGHP | LastGHP | 2097
您正在使用的方法 .next()
,它有默认的分隔符 whitespace
,所以它会读取并返回下一系列的字符串标记,直到到达空格。
在你的它将返回:
firstname =FirstNameFXO | LastFXO | 2510;
解决您的问题,您可以使用方法 读取每一行,然后将其保存在变量 Here is my program currently for retrieving data from the text file which looks like this: The input file looks like this: I am trying to print out just the firstName so I can use the values later for various other uses but it outputs this instead (the output is much larger, this is just the first three lines):
the problem that you are using method in your case it will return: to solve your problem instead you can use method read each line then save it in variable
这篇关于尝试存储来自文本文件的值,但输出不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! .nextLine() code
line
中并将其子字符串获取First Name :
while(s.hasNextLine()){
String line = s.nextLine();
字符串firstname = line.substring(0,line.indexOf(|));
System.out.println(First Name is+ firstName);
}
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
First Name is FirstNameFXO|LastFXO|2510
First Name is FirstNameXZU|LastXZU|2585
First Name is FirstNameGHP|LastGHP|2097
.next()
which has default delimiter whitespace
so it will read and return the next series of string token until a whitespace is reached.firstname ="FirstNameFXO|LastFXO|2510";
.nextLine()
line
and substring it to get the First Name: while(s.hasNextLine()){
String line = s.nextLine();
String firstname = line.substring(0,line.indexOf("|"));
System.out.println("First Name is " + firstName);
}