-1

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
  • The default delimiter for `next()` is whitespace. Where is the first whitespace in `FirstNameFXO|LastFXO|2510 Main Street|Suite 101D|City100|GA|72249|$280.80`? – azurefrog Mar 23 '17 at 16:47
  • Oh wow that makes a lot of sense, but how would I change it so it understands that the character "|" separates them. I tried inputting "|" in s.hasNext but it did not output anything – BastionOnly Mar 23 '17 at 16:48
  • Click the link behind "Possible duplicate of" ^^^ – Fildor Mar 23 '17 at 17:25

1 Answers1

0

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);
 }
Oghli
  • 1,585
  • 1
  • 9
  • 29