Why is my program printing values without a corresponding print statement?

Ganlas :

I am trying to figure out how to read in a series of values from a file in java. The file has multiple lines and the values are separated with commas in each line. While writing a test program just to figure out how to use a delimiter with Scanner I ran into an issue with my program printing values from the file. I don't know where the program is getting instructions to print all the values from.

This is what is in my public static void main (inside a try loop):

File f1 = new File("Data1.txt");
File test = new File("test.txt");
Scanner reader = new Scanner(f1);
Scanner testReader = new Scanner(test);
testReader.useDelimiter(",");

System.out.println("line 18 "+testReader.nextInt());
System.out.println("line 19 "+testReader.nextInt());
System.out.println("line 20 "+testReader.next());
System.out.println("line 21 "+testReader.nextInt());

The file I am reading from is test.txt:

4,5,6 
7 
8,9,10

And this is what is being printed:

line 18 4
line 19 5
line 20 6
7
8
line 21 9
s.fuhrm :

Your scanner is not seeing the linefeed characters as delimiters. This is the reason why the linefeed characters get returned by scanner.next()

Solution is to configure the scanner to have space and comma as delimiters:

testReader.useDelimiter("(,|\\s)");

See here for more info on patterns like "(,|\\s)".

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=27041&siteId=1