2015-03-02 2 views
1

Это мой CSV данные:неэффективно перекручивание в Java

Name,Code,Price,Colour,Type,Stock 
A,1001,35000,Red,Car Paint,54 
B,1002,56000,Blue,House Paint,90 

Как вы можете видеть, мое кодирование является неэффективным.

Это происходит потому, что все текстовые поля в NetBeans не позволяют те же имена переменных, я должен дать различные имена переменных для каждого текстового поля (пример: code1, code2, code3, name1, name2, name3)

Может кто-то помогает мне в том, как зацикливать эти данные, чтобы они делали это четыре раза, и мне не нужно повторять кодировку? и пропустить процесс, если поля пусты.

Ниже мое кодирование:

try 
    { 
     for(int z=0; z<4;z++) 
     { 
     String code1; 
     code1=this.text1.getText(); 
     System.out.println("this is the code: " + code1); 
     String qty; 
     int qty1; 
     qty=this.quantity1.getText(); 
     qty1=Integer.parseInt(qty); 
     System.out.println("quantity: "+qty1); 

     String code2; 
     code2=this.text2.getText(); 
     System.out.println("this is the code: " + code2); 
     int qty2; 
     qty=this.quantity2.getText(); 
     qty2=Integer.parseInt(qty); 
     System.out.println("quantity: "+qty2); 

     String code3; 
     code3=this.text3.getText(); 
     System.out.println("this is the code: " + code3); 
     int qty3; 
     qty=this.quantity2.getText(); 
     qty3=Integer.parseInt(qty); 
     System.out.println("quantity: "+qty3); 

     String code4; 
     code4=this.text4.getText(); 
     System.out.println("this is the code: " + code4); 
     int qty4; 
     qty=this.quantity2.getText(); 
     qty4=Integer.parseInt(qty); 
     System.out.println("quantity: "+qty4); 

     int sum=0; 

     BufferedReader line = new BufferedReader(new FileReader(new File("C:\\Users\\Laura Sutardja\\Documents\\IB DP\\Computer Science HL\\cs\\product.txt"))); 
     String indata; 

     ArrayList<String[]> dataArr = new ArrayList<>(); 
     String[] club = new String[6]; 
     String[] value; 
     while ((indata = line.readLine()) != null) { 
      value = indata.split(","); 
      dataArr.add(value); 
     } 

     for (int i = 0; i < dataArr.size(); i++) { 
      String[] nameData = dataArr.get(i); 
      if (nameData[1].equals(code1)) { 
       System.out.println("Found name."); 
       name1.setText(""+ nameData[0]); 
       int price; 
       price=Integer.parseInt(nameData[2]); 
       int totalprice=qty1*price; 
       String total=Integer.toString(totalprice); 
       price1.setText(total); 
       sum=sum+totalprice; 
       break; 
      } 
     } 

     for (int i = 0; i < dataArr.size(); i++) { 
      String[] nameData = dataArr.get(i); 
      if (nameData[1].equals(code2)) { 
       System.out.println("Found name."); 
       name2.setText(""+ nameData[0]); 
       int price; 
       price=Integer.parseInt(nameData[2]); 
       int totalprice=qty2*price; 
       String total=Integer.toString(totalprice); 
       price2.setText(total); 
       sum=sum+totalprice; 
       break; 
      } 
     } 

     for (int i = 0; i < dataArr.size(); i++) { 
      String[] nameData = dataArr.get(i); 
      if (nameData[1].equals(code3)) { 
       System.out.println("Found name."); 
       name3.setText(""+ nameData[0]); 
       int price; 
       price=Integer.parseInt(nameData[2]); 
       int totalprice=qty3*price; 
       int totalprice3=totalprice; 
       String total=Integer.toString(totalprice); 
       price3.setText(total); 
       sum=sum+totalprice; 
       break; 
      } 
     } 

     for (int i = 0; i < dataArr.size(); i++) { 
      String[] nameData = dataArr.get(i); 
      if (nameData[1].equals(code4)) { 
       System.out.println("Found name."); 
       name4.setText(""+ nameData[0]); 
       int price; 
       price=Integer.parseInt(nameData[2]); 
       int totalprice=qty4*price; 
       int totalprice4=totalprice; 
       String total=Integer.toString(totalprice); 
       price4.setText(total); 
       sum=sum+totalprice; 
       break; 
      } 
     } 


     total1.setText("Rp. "+sum); 
    } 
    } 

    catch (IOException iox) 
    { 
     System.out.println("Error"); 
    } 
+0

что значение 'code1' ?? 'if (nameData [1] .equals (code1))' есть некоторая проблема с этой строкой. – Prashant

+0

code1 - пользовательский ввод. если соответствует пользовательскому вводу с существующим файлом csv, поскольку он должен отображать данные из другого столбца, такие как nameData [0] –

+0

, можете ли вы использовать библиотеку типа spring? –

ответ

0

Решение этой проблемы на самом деле довольно прямо вперед, если разбить его на отдельные части.

Прежде всего вам необходимо решить проблему загрузки данных во внутреннее представление данных, которое прост в использовании. Просто загрузки файла в Java довольно прост, и вы уже сделали это:

BufferedReader csvFile = new BufferedReader(new FileReader(new File(path))); 
String line = "start"; 
int count = 0; 
while((line = csvFile.readLine()) != null){ 
    System.out.println(line); 
} 
csvFile.close(); 

Следующая проблема разделения линии и хранить его осмысленно - для каждой строки.

HashMap<Integer, String> record = new HashMap<Integer, String>(); 
String[] raw = line.split(","); 
for(int i=0;i<raw.length; i++){ 
    record.put(i, raw[i]); 
} 

Теперь вы утверждаете, вы только хотите, чтобы хранить записи, которые имеют непустые поля, поэтому мы должны проверить, что:

HashMap<Integer, String> record = new HashMap<Integer, String>(); 
String[] raw = line.split(","); 
Boolean store = true; 
for(int i=0;i<raw.length; i++){ 
    if(raw[i].equals("") || raw[i].equals(null)){ 
     store = false; 
     break; 
    } 
    record.put(i, raw[i]); 
}   
if(store) 
    csvData.add(record); 

Теперь вы можете загружать каждую запись файла CSV как словарь, который вы можете легко использовать. Осталось только сохранить список этих словарей.

ArrayList<Map<Integer, String>> csvData = new ArrayList<Map<Integer, String>>(); 

BufferedReader csvFile = new BufferedReader(new FileReader(new File(path))); 
String line = "start"; 
int count = 0; 
while((line = csvFile.readLine()) != null){ 
    if(count == 0){//skip first line 
     count++; 
     continue; 
    } 

    HashMap<Integer, String> record = new HashMap<Integer, String>(); 
    String[] raw = line.split(","); 
    Boolean store = true; 
    for(int i=0;i<raw.length; i++){ 
     if(raw[i].equals("") || raw[i].equals(null)) 
     { 
      store = false; 
      break; 
     } 
     record.put(i, raw[i]); 
    } 
    if(store) 
     csvData.add(record); 
    } 
csvFile.close(); 

Полный фрагмент кода, который загружает в данных и легко получить доступ к любой информации, вы хотите:

public class Main { 
public static final int NAME = 0; 
public static final int CODE = 1; 
public static final int PRICE = 2; 
public static final int COLOR = 3; 
public static final int TYPE = 4; 
public static final int STOCK = 5; 

public static void main(String[] args) throws IOException{ 
    ArrayList<Map<Integer, String>> csvData = loadCSVFile("C:\\path\\to\\file\\products.txt"); 

    //Print some of the data 
    System.out.println("---------------------------"); 
    for(Map<Integer, String> record : csvData){ 
     printInfo(record); 
    } 
} 

public static ArrayList<Map<Integer, String>> loadCSVFile(String path) throws IOException{ 
    ArrayList<Map<Integer, String>> csvData = new ArrayList<Map<Integer, String>>(); 

    BufferedReader csvFile = new BufferedReader(new FileReader(new File(path))); 
    String line = "start"; 
    int count = 0; 
    while((line = csvFile.readLine()) != null){ 
     if(count == 0){ 
      count++; 
      continue; 
     } 

     HashMap<Integer, String> record = new HashMap<Integer, String>(); 
     String[] raw = line.split(","); 
     Boolean store = true; 
     for(int i=0;i<raw.length; i++){ 
      if(raw[i].equals("") || raw[i].equals(null)) 
      { 
       store = false; 
       break; 
      } 
      record.put(i, raw[i]); 
     } 

     if(store) 
      csvData.add(record); 
    } 
    csvFile.close(); 
    return csvData; 
} 

public static void printInfo(Map<Integer, String> record){ 
    System.out.println(record.get(CODE) + " : " + record.get(TYPE)); 
    System.out.println(record.get(NAME) + " : " + record.get(STOCK) + " : " + record.get(PRICE)); 
    System.out.println("---------------------------"); 
} 

} 
Смежные вопросы