我有个让我烦恼的问题。我有一个.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停止。因此,如何使用定界符在最后一个*中停止循环并避免在额外的/有问题的时间内输入它?

我已经尝试过类似的东西

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);
    }
}


谢谢所有帮助我的人。

最佳答案

您可能想在正则表达式中避开星星:

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

因为

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

09-16 03:46
查看更多