Trying to store values from a a text file but it outputting incorrectly [duplicate]

纵然是瞬间 提交于 2019-12-25 18:23:10

问题


Here is my program currently for retrieving data from the text file which looks like this:

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();

The input file looks like this:

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

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):

First Name is FirstNameFXO|LastFXO|2510
First Name is FirstNameXZU|LastXZU|2585
First Name is FirstNameGHP|LastGHP|2097

回答1:


the problem that you are using method .next() which has default delimiter whitespace so it will read and return the next series of string token until a whitespace is reached.

in your case it will return:

firstname ="FirstNameFXO|LastFXO|2510";

to solve your problem instead you can use method .nextLine()

read each line then save it in variable 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);
 }


来源:https://stackoverflow.com/questions/42982158/trying-to-store-values-from-a-a-text-file-but-it-outputting-incorrectly

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!