简体   繁体   中英

inefficient looping in java

This is my csv data:

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

As you can see, my coding is inefficient.

This is because all the textfields in netbeans do not allow same variable names, I have to give different variable names to each text field (Example: code1, code2, code3, name1, name2,name3)

Can someone help me on how to loop this data so they do it four times and i dont have to repeat the coding? and to skip the process if the fields are blank.

The following is my coding:

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");
    }

Solving this problem is actually rather straight forward if you break it down into separate parts.

First you need to solve the problem of loading the data into an internal data representation that is easy to use. Just loading the file into Java is rather simple and you have already done this:

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();

The next problem is splitting the line and store it in a meaningful way - for each line.

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]);
}

Now you state you only want to store records that have non-empty fields so we need to check for that:

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);

Now, you can load each record of the csv file as a dictionary that you can easily use. All that remains is to save a list of these dictionaries.

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();

Full code snippet that loads in data and easily access whatever information you want:

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("---------------------------");
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM