pwhockey61:
私は、データの乱雑なセットを与えられ、カテゴリにデータを分割する必要がありいます。最初の行は次の行は、「アイテム」、「アイテムの数、」価格(列)ことになっている、税率です。私はちょうどそれに応じて、ヘルプの分割データを必要とします。任意の助けいただければ幸いです。
0.05 5
Colored Pencils 3 0.59
Notebook 5 0.99
AAA Battery 5 0.99
Java Book 5 59.95
iPhone X 2 999.99
iPhone 8 3 899.99.
import java.io.*;
import java.util.Scanner;
public class ShoppingBagClient {
public static void main(String[] args) {
File file = new File("data.txt");
shoppingBag(file);
}
public static void shoppingBag (File file) {
Scanner scan;
String itemName=" ";
int quantity = 0;
float price = 0;
int count = 0;
float taxRate;
ShoppingBag shoppingBag = new ShoppingBag(6, .5f);
try {
scan = new Scanner(new BufferedReader(new FileReader(file)));
String dilimeter;
while(count < 1) {
String line = scan.nextLine();
String[] arr = line.split(" ");
taxRate = Float.parseFloat(arr[0]);
}
while(scan.hasNextLine() && count > 0){
String line = scan.nextLine();
String delimeter;
String arr[] = line.split();
itemName = arr[0];
quantity = Integer.parseInt(arr[1]);
price = Float.parseFloat(arr[2]);
Item item =``` new Item(itemName, quantity, price);
shoppingBag.push(item);
System.out.println(itemName);
}
}
catch(IOException e) {
e.printStackTrace();
}
}
}
ジェームズ・バーチ:
ヘンリーさんのコメント@良いアプローチを提供します。あなたが(例えば、単一のスペースで区切られた)を、各ラインの構造を知っているし、それは一貫した方法で区切られていることなら、あなたはのlastIndexOfを組み合わせて、仕事をするためにサブストリングができます。
String delimiter = " ";
String line = scan.nextLine(); // "Colored pencils 3 0.59"
int last = line.lastIndexOf(delimiter); // "Colored pencils 3_0.59"
String price = line.substring(last + 1); // "0.59"
line = line.substring(0, last); // "Colored pencils 3"
last = line.lastIndexOf(delimiter); // "Colored pencils_3"
String quantity = line.substring(last + 1); // "3"
line = line.substring(0, last); // "Colored pencils"
String product = line;
これは、整然とするリファクタリングが、ポイントを説明することができます。lastIndexOfは、行の最後の文字を返す場合は、その注意してsubstring(last + 1)
StringIndexOutOfBoundsExceptionをスローされます。チェックものlastIndexOfが、それは-1を返します。その場合には、一致を見つけることができなかった場合のために取られるべきです。
編集:価格と数量は、必要に応じてintまたはfloat型に変換することができます。