扫描器类别中使用分隔符的问题

问题描述

|
    try {
    Scanner in = new Scanner(new File(\"text.txt\"));

    Formatter out = new Formatter(\"text1.txt\");
    in.useDelimiter(\",\");
    int num = in.nextInt();//this line throws null exception
    for(int i = 0; i < num && in.hasNext(); i++)
    {

        out.format(\"%s\",\"#string \\n\" + i );

        out.format(\"%s\",in.next());


    }
    out.close();
    }
     catch (Exception e) {
         System.out.print(e.getMessage());
    }
输入为:
    4
hello,my,name,is
4是单词数。 输出必须是:
hello my name is
但是它抛出了异常,误差ѭ3。 有什么问题     

解决方法

您必须在4方法中使用适当的正则表达式。下面的代码应该工作:
try {
    Scanner in = new Scanner(new File(\"text.txt\"));
    Formatter out = new Formatter(\"text1.txt\");
    in.useDelimiter(\",|\\n|\\r\\n|\\\\s+\");
    int num = in.nextInt();
    for(int i = 0; i < num && in.hasNext(); i++)
        out.format(\"string # %d is: [%s]\\n\",i,in.next() );
    out.close();
}
catch (Exception e) {
    System.err.print(\"Exception: \" + e);
}
输出量 对于给定的输入
4
hello,my,name,is
它输出:
string # 0 is: [hello]
string # 1 is: [my]
string # 2 is: [name]
string # 3 is: [is]
    ,问题在于,当您指定定界符为逗号时,换行符不再是定界符。 将文件更改为4,hello,my,name,is,它应该可以工作。     

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...