I have a problem that’s breaking my mind. I have a .txt file that looks like
fiat,regata,15*renault,seiscientos,25*
In my code I have this
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);
}
The problem here is that the While loop is working three times, so the third time marca=\n and It stops with a java.util.NoSuchElementException. So, How can I use my delimiter to stop de loop in the last * and avoid It to enter in that extra/problematic time?.
I already tried things like
while(sc.next!="\n")
I also triyed this and doesn’t work
sc.useDelimiter(“[,\*\n]”);
SOLVED!!!
I finally found the solution, in part thanks to the advice of user1542723. The solution
is:
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);
}
}
Thank you everybody who helped me.
You may want to escape the star in your regex:
sc.useDelimiter("[,\\*]");Because
"[,*]"means,zero or more times and"[,\\*]"means,or*.