【问题标题】:Java Scanner Delimiter without \n没有 \n 的 Java 扫描仪分隔符
【发布时间】:2012-11-03 14:49:29
【问题描述】:

我有一个让我心烦意乱的问题。我有一个 .txt 文件,看起来像

fiat,regata,15*renault,seiscientos,25*

在我的代码中我有这个

       Scanner sc=new Scanner(new File("coches.txt");
        sc.useDelimiter("[,*]");
        while(sc.hasNext()){   
            marca=new StringBuffer(sc.next());
            modelo=new StringBuffer(sc.next());
            marca.setLength(10);
            modelo.setLength(10);
            edad=sc.nextInt();

            coche=new Coche(marca.toString(),modelo.toString(),edad);
            coches.add(coche);
        }

这里的问题是 While 循环工作了三次,所以第三次 marca=\n 并以 java.util.NoSuchElementException 停止。那么,如何使用我的分隔符在最后一个 * 中停止 de 循环并避免它进入那个额外/有问题的时间?

我已经尝试过类似的东西

while(sc.next!="\n")

我也试过了,还是不行

sc.useDelimiter("[,\*\n]");

解决了!!!

我终于找到了解决方案,部分归功于 user1542723 的建议。解决方案
是:

String linea;
String [] registros,campos;    
File f=new File("coches.txt");
FileReader fr=new FileReader(f);
BufferedReader br=new BufferedReader(fr);//ALL this need Try Catch that I'm not posting

while((linea=br.readLine())!=null){
        registros=linea.split("\\*");
    }
    for (int i = 0; i < registros.length; i++) {
        campos=registros[i].split(",");
        marca=campos[0];
        modelo=campos[1];
        edad=Integer.parseInt(campos[2]);//that's an Int, edad means Age

        coche=new Coche(marca.toString(),modelo.toString(),edad);
        coches.add(coche);
    }
}

感谢所有帮助过我的人。

【问题讨论】:

    标签: java java.util.scanner delimiter


    【解决方案1】:

    你可能想在你的正则表达式中转义星号:

    sc.useDelimiter("[,\\*]");

    因为

    "[,*]" 表示, 零次或多次,"[,\\*]" 表示,*

    【讨论】:

    • 好的,我做到了,但我仍然遇到同样的问题。
    • 如果添加任何空格怎么办?喜欢sc.useDelimiter("[,\\*\\s+]");
    • 你为什么不用扫描仪读取完整的一行,用"\\*"分割它,然后用","分割结果?
    【解决方案2】:

    您可以使用String.split("\\*") 首先在 * 处拆分,然后每个记录都有 1 个数组条目,然后再次使用 split(",") 来获取您现在拥有的所有值。

    示例:

    String input = "fiat,regata,15*renault,seiscientos,25*";
    String[] lines = input.split("\\*");
    for(String subline : lines) {
        String[] data = subline.split(",");
        // Do something with data here
        System.out.println(Arrays.toString(subline));
    }
    

    【讨论】:

    • 谢谢哥们,你给了我线索。
    猜你喜欢
    • 2014-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多