简体   繁体   English

Java Scanner Delimeter无法按我预期的方式工作

[英]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);
        input.useDelimiter(":");
        while (input.hasNextLine()) {
            input.next();
            line = input.nextLine();
            try{
                totalSales += Double.parseDouble(line);
                count++;
            }
            catch(IllegalArgumentException e){
                missingCount++;
            }

        }
        input.close();

    } catch (Exception ex) {
        ex.printStackTrace();
    }
    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. 但是,当我运行该程序时,它会打印出0.0 3,就像所有的东西一样丢失。 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 问题是当我运行调试器以查看行中发生了什么时,所以parseDouble无法运行,并且我看到该行是具有此内容的字符串

: 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. ps:这是一本书的练习,很简单,但是书中使用了由他们实现的TextIO类。 just wanted to try scanner instead of their code. 只是想尝试使用扫描仪而不是他们的代码。

Scanner#nextLine grabs the rest of the line, regardless of the delimiter. 无论分隔符如何, Scanner#nextLine抓取其余的行。

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 扫描仪#nextLine

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM