zzzzz
zzzzz

Reputation: 87

Using 2D array to store a portion of a line

I have a .txt that contains

bananas, 1, 15
dogs, 1, 10
cats, 1, 5

Using the split(", ") method, I was able to get the first 15 in the first row in my array String[] price , but I want to store the last two numbers as well. I was thinking a 2D array in which

price[0][2] = 15,
price[1][2]=10
price[2][2] = 5

and parsing the three as a double and adding them together. I have this,

while ((linePrice = totalReader.readLine()) != null) {
    price1 = linePrice.split(", ");
    if ((line = totalReader.readLine()) != null) {
        price2 = linePrice.split(", ");
    }
    if ((line = totalReader.readLine()) != null) {
        price2 = linePrice.split(", ");
    }
}

but it accomplishes nothing because all three of the prices are just the first, 15.

Upvotes: 0

Views: 42

Answers (1)

sagarr
sagarr

Reputation: 1212

You need to simply iterate over each line from text file and grab price by splitting line on , and append to price array, below pseudo code get you started

String[] prices = new String[3];
int i = 0;
while ((linePrice = totalReader.readLine()) != null) {
    String[] array = linePrice.split(", ");
    prices[i] = array[2]; // third index contain price
    i++;
}

Upvotes: 1

Related Questions