頭がおかしくなる問題があります。次のような.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ループが3回機能しているため、3回目は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);
}
}
助けてくれた皆さん、ありがとうございました。