string.split() with columns

given the following text file

91607,apple,20.0,s201
29305,orange,10.0,s234
19275,banana,30.0,s654
10873,plum,10.0,s123

How would I deal with the columns so that I could:
list a column:
 91607
 29305
 19275
 10873

add the 3rd columns up:
 70.0

print the number of lines:
 4
import java.io.*;
import java.util.*;

public class Sample {

 public static void main(String[] args) {


String csv = null;
String file = null;
int count = 0;

BufferedReader buff = new BufferedReader(new InputStreamReader(System.in));

  try {
   file = buff.readLine();
  } catch (IOException e) {
   System.out.print(file + " does not exist");
  System.exit(1);
  }

  try {
     BufferedReader in =  new BufferedReader(new FileReader(new File(file))); 
        try {
           while (( csv = in.readLine()) != null){   

     // How would I seperate it here? 
     // I'm trying to use string.split()
             
          }
        }
        finally {
          buff.close();
        }
        
      }
        catch (IOException e){  
        System.out.print("failed to open " + file + "\n");
      }
 }
}

Open in new window

Marketing_InsistsAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

objectsCommented:
String[] columns = csv.split(",");
0
HyperBPPCommented:

int sum = 0;
try { 
	while (( csv = in.readLine()) != null){    
		count++;
		String[] columns = csv.split(",");
		System.out.println(columns[0]);
		sum+=columns[2];
	} 
}finally {
	buff.close(); 
} 
System.out.println("Line Count: " + count);
System.out.println("Sum: " + sum);

Open in new window

0
Arabia_vnCommented:
I've read all the code and think that it's impossible to do the job. I think need to save the split function of all columns which make me think of an array of string array (kinda stupid but at least it works);

Here's an example (Note that code below has not optimized yet, first it reads total number of columns for initializing the array and after that it does the job. That's why it looks kinda stupid like i said)
import java.io.*;
import java.util.*;

public class Sample{

 public static void main(String[] args) {


String csv = null;
String file = null;
int count = 0;
int numberofcolumn = 0;
String [] [] arrayofcolumn; //<--- add 1 more variable;

BufferedReader buff = new BufferedReader(new InputStreamReader(System.in));

  try {
   file = buff.readLine();
  } catch (IOException e) {
   System.out.print(file + " does not exist");
  System.exit(1);
  }

  try {
     BufferedReader in =  new BufferedReader(new FileReader(new File(file)));
        try {
           while (( csv = in.readLine()) != null){  

                 numberofcolumn++; //<--- first open the file just for taking the number of columns for initializing the array;
             
          }
        }
        finally {
          buff.close();
        }
       
      }
        catch (IOException e){  
        System.out.print("failed to open " + file + "\n");
      }

        arrayofcolumn = new String[numberofcolumn][]; //<--- initializing the array

        try {
            BufferedReader in =  new BufferedReader(new FileReader(new File(file)));
               try {
                  while (( csv = in.readLine()) != null){  

                        arrayofcolumn[count] = csv.split(",");  // <--- open file the second time to save what we need to array, that's //why i said my example is stupid
                    count++;
                 }
               }
               finally {
                 buff.close();
               }
               
             }
               catch (IOException e){  
               System.out.print("failed to open " + file + "\n");
             }
// Now everything is saved, we can do whatever we want
               for (int i=0;i<=count;i++)
               {
                     System.out.println(arrayofcolumn[i][0]);

               }
 }
}
0
Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

CEHJCommented:
>>How would I deal with the columns so that I could:

You want to treat the data as a table essentially, so you should probably use a DefaultTableModel, whether or not you want to display it in a Swing gui, but especially if you do
0
Marketing_InsistsAuthor Commented:
wow, at least it isn't easy! :-) I appreciate your efforts - I'm taking a night class in java.

By what I've learned so far, something as in the below could be in order, but I've not been able to get it to work either.
//fail
int sum = 0;
while (( csv = input.readLine()) != null){ 

          String[] columns = csv.split(",");
          
          String col_0 = columns[0];
          col_0a.add (col_0);
          
          Double col_2 = Double.parseDouble(columns[2]);
          sum += (col_2);

          count++;
}

Open in new window

0
CEHJCommented:
Another approach would be to treat each row as an object instance and add to a collection. What do the numbers represent?
0
objectsCommented:
better off using double for sum:

double sum = 0;
while (( csv = input.readLine()) != null){

          String[] columns = csv.split(",");
          if (columns.length==4) {
             String col_0 = columns[0];
             col_0a.add (col_0);
         
             double col_2 = Double.parseDouble(columns[2]);
             sum += col_2;

             count++;
         }
}
System.out.println("Number of rows: "+count);
System.out.println("Sum: "+sum);
0
CEHJCommented:
If you make a bean called Fruit, as in my last suggestion, the following is an example of what you can do:
import java.io.*;

import java.util.*;


public class Fruits {
    private List<Fruit> fruits;

    public void load(String fileName) throws IOException {
	fruits = new ArrayList<Fruit>();

	Scanner s = null;

	try {
	    s = new Scanner(new File(fileName));
	    s.useDelimiter("[,\r\n]");

	    while (s.hasNextInt()) {
		fruits.add(new Fruit(s.nextInt(), s.next(), s.nextDouble(), s.next()));
	    }
	} finally {
	    if (s != null) {
		s.close();
	    }
	}
    }

    public double getTotalPrice() {
	double result = 0.0;

	for (Fruit f : fruits) {
	    result += f.getPrice();
	}

	return result;
    }

    public static void main(String[] args) {
	try {
	    Fruits data = new Fruits();
	    data.load(args[0]);
	    System.out.println(data.getTotalPrice());
	} catch (IOException e) {
	    e.printStackTrace();
	}
    }
}

Open in new window

0
Marketing_InsistsAuthor Commented:
Almost got it:

Trying to understand/implement:
  ArrayList<String> col_0a = new ArrayList<String>();
for the first column col_0a

Just a tiny bit of trouble getting to print out.
import java.io.*;
import java.util.*;

// ALMOST WORKS
public class Sample {

 public static void main(String[] args) {


String csv = null;
String file = null;
int count = 0;
int sum=0;
ArrayList<String> col_0a = new ArrayList<String>();

BufferedReader buff = new BufferedReader(new InputStreamReader(System.in));

  try {
   file = buff.readLine();
  } catch (IOException e) {
   System.out.print(file + " does not exist");
  System.exit(1);
  }

  try {
     BufferedReader in =  new BufferedReader(new FileReader(new File(file))); 

        try { 
        
        while (( csv = in.readLine()) != null){
             String[] columns = csv.split(",");
             if (columns.length==4) {
             String col_0 = columns[0];
             col_0a.add (col_0);
         
             double col_2 = Double.parseDouble(columns[2]);
             sum += col_2;

             count++;
             }
        } 
        
        }finally {
        buff.close(); 
} 
        System.out.println("Line Count: " + count); // hurray!
        System.out.println("Sum: " + sum);          // hurray!
        System.out.println("Col 0 \n" + col_0a);     //boo - gives [91607, 29305, 19275, 10873] 
        
        // I'm confused about ArrayList<String> : so is col_0a an array?
        // Regardless, how can I print out the contents of col_0a like so:
        // 91607
        // 29305
        // 19275
        // 10873
        
         /*  int i =0;
           for (i = 0; i < col_0a.length; i++) {
            System.out.print(col_0a[i]);
        }*/
           
      }
        catch (IOException e){  
        System.out.print("failed to open " + file + "\n");
      }
 }
}

Open in new window

0
VenabiliCommented:
The ArrayList is a list, not an array. So you can either use:

for (int i = 0; i < col_0a.size(); i++) {
       System.out.println(col_0a.get(i));
 }

or use an Iterator - http://www.java2s.com/Code/JavaAPI/java.util/ArrayListiterator.htm
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Marketing_InsistsAuthor Commented:
So close, I can taste it:

OK!  tried that and the iterator as you sugested: but I'm getting a out of bounds error for either of the below:
java.lang.ArrayIndexOutOfBoundsException: 4

//tried
for (int i = 0; i < col_0a.size(); i++) {
       System.out.println(col_0a.get(i));
 }

// and tried
    Iterator<String> itr = col_0a.iterator();
    while (itr.hasNext()) {
      String element = itr.next();
      System.out.print(element + "\n");
    }
0
Marketing_InsistsAuthor Commented:
The complaint being from the while statement line:
col_0a.add (col_0);
0
VenabiliCommented:
Any of these print your arrayList. But use println if you want them on separate lines, not print :)

col_0a.add (col_0);Says OutOFBoundException? That's impossible.

Please your full current code and the exact error.
0
Marketing_InsistsAuthor Commented:
Ah, I changed if (columns.length==4)   to  (columns.length>=4) for the win.
0
VenabiliCommented:
If that helps, this means that the code that you use is not the one above...
0
objectsCommented:
> Ah, I changed if (columns.length==4)   to  (columns.length>=4) for the win.

that just suggests your input file has some rows with more than 4 columns

0
VenabiliCommented:
Even if this is so, it would not have thrown OutOfBoundException :)
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.