Reputation: 47
I have a string currLine = "0 1435 " 3029 " "(1975.92)" " 72,304""
(there are quotations within the string) and I want to print out all of the integers in currLine. But with the code below, I only get the number 0 printed out. How do I use nextInt() so that it prints out all of the integers?
Scanner scanLine = new Scanner(currLine);
while (scanLine.hasNext()) {
if (scanLine.hasNextInt()) {
System.out.println(scanLine.nextInt());
}
scanLine.next();
}
Upvotes: 1
Views: 376
Reputation: 129497
As soon as the Scanner
encounters something that isn't an int, hasNextInt()
returns false
. Not to mention the fact that you're skipping over some valid ints with the scanLine.next()
call at the bottom of your while
-loop. You can use a Matcher
instead:
Matcher m = Pattern.compile("\\d+").matcher(currLine);
while (m.find()) {
System.out.println(m.group());
}
0 1435 3029 1975 92 72 304
Upvotes: 4
Reputation: 2040
Actually, else
word is missing too. No need to do next()
if nextInt()
done.
Upvotes: 1
Reputation: 28
I believe next() goes until it sees a space. I would use replace("\"",""), rinse and repeat with other characters until you have a string of the integers you can print.
Upvotes: 0