hzzhyj hzzhyj - 1 year ago 86
Java Question

Java Scanner Delimeter not working as I expected

I have got a question about a code I have written

package salescities;
import java.io.File;
import java.util.Scanner;

public class SalesCities {

* @param args the command line arguments
public static void main(String[] args) {
double totalSales = 0;
int count = 0;
int missingCount = 0;
String line;
File file;
Scanner input;
try {

file = new File("sales.txt");
input = new Scanner(file);
while (input.hasNextLine()) {
line = input.nextLine();
totalSales += Double.parseDouble(line);
catch(IllegalArgumentException e){


} catch (Exception ex) {
System.out.println(totalSales + " " +missingCount);


And the file im trying to read is like this

New York: 23.5678
New Jersey: no reports
Rio de Janeiro: 12.3654

When i run the program however it prints out 0.0 3 like all is missing.
The problem is when i run the debugger to see whats happening to line so parseDouble isn't functioning and i saw that line is a string that has this

: 23.5678

and I don't understand why if I'm using ":" as delimeter. I expected only the number without the colon. Can someone answer me?

ps: this is an exercise from a book that's quite simple but the book uses a class TextIO that is implemented by them. just wanted to try scanner instead of their code.

Answer Source

Scanner#nextLine grabs the rest of the line, regardless of the delimiter.

Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line. — Scanner#nextLine

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download