2017-10-31 6 views
0

私は,\\sを区切りたいと思いますが、私も\nを区切りたいと思っていましたが、これまで考えていたのは,\\s||\nでした。もちろん、区切り文字として働いていたが、それは私が戻ってIPHONE 7, 4.7, A10, GSM, JET BLACK, 32GB, TRUE, 7002つ以上の区切り文字を使用する方法

を望む一方で、私はスキャンだファイルは、このバックIPHONE , 7.0, 4, ., 7, A, false, 0与えた:

IPHONE 7, 4.7, A10, GSM, JET BLACK, 32GB, TRUE, 700 
IPAD AIR 2, 9.7, A8, TRUE, SILVER, 64GB, 400 

私はそれをスキャンするために使用しているコードを、これです:

public static iPhone read(Scanner sc) { 
     boolean touchtech = false; 
     //int price = 12; 
     sc.next(); 
     sc.useDelimiter(",\\s||\n"); 
     String model = sc.next(); 
     double screensize = sc.nextDouble(); 
     String processor = sc.next(); 
     String modem = sc.next(); 
     String color = sc.next(); 
     String memory = sc.next(); 
     String touchtechtest = sc.next(); 
     if(touchtechtest.equals("TRUE")) { 
      touchtech = true; 
     } 
     int price = sc.nextInt(); 
     sc.close(); 
     iPhone res = new iPhone(model, screensize, processor, modem, color, memory, touchtech, price); 
     return res; 
    } 
+1

追加のコンテキストを提供する必要があります。 –

+0

スキャナから行全体を読み込んだ後、 'String.split()'を使って分割することができます。 – Jason

答えて

0

時々String.class自身がニーズを処理するのに十分以上のものです。正規表現を使用して代わりに行を分割し、その結果を操作するのはなぜですか?例えば

public static iPhone read(Scanner sc) { // Better yet just make it received a String 
    final String line = sc.nextLine(); 
    final String [] result = line.split("(,)\\s*"); 

    // count if the number of inputs are correct 
    if (result.length == 8) { 
     boolean touchtech = false; 
     final String model = result[0]; 
     final double screensize = Double.parseDouble(result[1]); 
     final String processor = result[2]; 
     final String modem = result[3]; 
     final String color = result[4]; 
     final String memory = result[5]; 
     final String touchtechtest = result[6]; 
     if(touchtechtest.equals("TRUE")) { 
      touchtech = true; 
     } 
     final int price = Integer.parseInt(result[7]); 
     return new iPhone(model, screensize, processor, modem, color, memory, touchtech, price); 
    } 
    return new iPhone();// empty iphone 
} 
0

useDelimiterは正規表現を受信します。したがって、あなたの場合、正しい文字列は"(,\\s|\n)"になります。あなたのOR条件は丸い括弧内に入り、二重パイプではなく一本のパイプで区切られています。

また、この優れた答えを参照することができます。 How do I use a delimiter in Java Scanner?

+0

私はちょうどそれを試みた、それは動作しませんでした。これは28行目のInputMismatchExceptionを与えます。この場合はint price = sc.nextInt();という行です。 –

+0

おそらく28行目が正しい形式ではありませんか? – dave

+0

正しい形式でなければなりません。私がそれを文字列に変換して、それを元に返します。これはint型ですか? –

関連する問題