0

頭がおかしくなる問題があります。次のような.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);
    }
}

助けてくれた皆さん、ありがとうございました。

4

2 に答える 2

1

正規表現で星をエスケープしたい場合があります。

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

なぜなら

"[,*]",0 回以上を"[,\\*]"意味 し,、 またはを意味し*ます。

于 2012-11-03T14:54:35.060 に答える
0

を使用し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));
}
于 2012-11-03T15:33:03.717 に答える