?
Solved

string.split() with columns

Posted on 2010-04-09
17
Medium Priority
?
456 Views
Last Modified: 2012-05-09
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

0
Comment
Question by:Marketing_Insists
  • 5
  • 4
  • 3
  • +3
17 Comments
 
LVL 92

Expert Comment

by:objects
ID: 30265581
String[] columns = csv.split(",");
0
 
LVL 6

Expert Comment

by:HyperBPP
ID: 30271676

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
 
LVL 8

Expert Comment

by:Arabia_vn
ID: 30277062
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
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

 
LVL 86

Expert Comment

by:CEHJ
ID: 30282224
>>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
 

Author Comment

by:Marketing_Insists
ID: 30282541
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
 
LVL 86

Expert Comment

by:CEHJ
ID: 30283564
Another approach would be to treat each row as an object instance and add to a collection. What do the numbers represent?
0
 
LVL 92

Expert Comment

by:objects
ID: 30289022
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
 
LVL 86

Expert Comment

by:CEHJ
ID: 30312777
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
 

Author Comment

by:Marketing_Insists
ID: 30332606
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
 
LVL 20

Accepted Solution

by:
Venabili earned 2000 total points
ID: 30333612
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
 

Author Comment

by:Marketing_Insists
ID: 30337528
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
 

Author Comment

by:Marketing_Insists
ID: 30337758
The complaint being from the while statement line:
col_0a.add (col_0);
0
 
LVL 20

Expert Comment

by:Venabili
ID: 30338043
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
 

Author Comment

by:Marketing_Insists
ID: 30338281
Ah, I changed if (columns.length==4)   to  (columns.length>=4) for the win.
0
 
LVL 20

Expert Comment

by:Venabili
ID: 30338684
If that helps, this means that the code that you use is not the one above...
0
 
LVL 92

Expert Comment

by:objects
ID: 30345882
> 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
 
LVL 20

Expert Comment

by:Venabili
ID: 30346165
Even if this is so, it would not have thrown OutOfBoundException :)
0

Featured Post

Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
Suggested Courses
Course of the Month7 days, 4 hours left to enroll

592 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question