2

My input file look like this:

1,2,3,4,5,6
3,4,5,6,7,8
5,6,7,8,9,9
1,2,3,4,5,6

I want to count the number of word in a column and the number of rows so that I can know the array size and put them into a 2D array.

How can I get the number of column and rows? Thanks!!!!

My code:

public static void main(String[] args) throws IOException {

        File file = new File("test.txt");
        Scanner input = new Scanner(file);
        BufferedReader bufRdr  = new BufferedReader(new FileReader(file));
        String line = null;

        int i = 0;
        int j = 0;
        int row = 0;
        int col = 0;
        String [][] data = new String [i][j];


        while((line = bufRdr.readLine()) != null)
        {   
        StringTokenizer st = new StringTokenizer(file,",");

        while (st.hasMoreTokens()){ 
          i++;
        }
        while(input.hasNextLine()) {

          String tmp=input.nextLine();

          j++;

        }
        System.out.println(i);
        System.out.println(j);
1
  • 2
    Why don't you use a dynamic data structure like a List<List<Object>>>? Jan 12, 2012 at 4:01

7 Answers 7

2

I like shorter answers. ;) This reads the text, removes spaces and builds an int[][] from the text.

List<int[]> list = new ArrayList<>();
for(String line: FileUtils.readLines("test.txt")) {
    String[] words = line.split(",");
    int[] nums = new int[words.length];
    for(int j=0;j<nums.length;j++)
       nums[i] = Integer.parseInt(words[i].trim());
}
int[][] matrix = list.toArray(new int[list.size()][]);
1
  • 1
    :-) no doubt short one is better. + 1 for that. Regards
    – nIcE cOw
    Jan 20, 2012 at 12:58
1

Okay, firstly, surely you could use a dynamic data structure? I'm assuming you don't know beforehand how many columns or rows you're going to read. That means you don't know how to big to make your array, unless you want to make one redundant parse through your data. If you use a dynamic data structure, that won't be a problem.

The majority of dynamic data structures that are commonly used in Java reside in the Collections package.

This will make your task much easier. I've tried coding up a sample solution to the problem you asked. It is by no means actually good code, and I'm currently at work so I've thrown it together rather hastily. Please ask if there's something that doesn't make sense.

File file = new File("test.txt");
Scanner input;
try {
    input = new Scanner(file);
} catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    System.exit(1);
    return; //I'm just hacking this to get around Eclipse being derpy
}

List<List<Integer> > arrList = new ArrayList<ArrayList<Integer> >();
//this is a kinda dynamic 2D array, it's not very pretty though, and I'm sure there are
//better ways than how I'm doing it here

while(input.hasNextLine()) {
    String tmp=input.nextLine();
    String[] splitAtComma = tmp.split(","); //break the String into a separate entry every time you see
    arrList.add(new ArrayList<Integer>());
    for(String s : splitAtComma) {
        arrList.get(arrList.size()-1).add(Integer.parseInt(s));
    }
}
Integer[][] finalAnswer = new Integer[arrList.size()][]; //couldn't figure out a way to get it to end up as int[][]
for(int i = 0; i < finalAnswer.length; i++) {
    finalAnswer[i] = arrList.get(i).toArray(new Integer[0]);
}

//a for-each loop
for(Integer[] i : finalAnswer) {
    for(Integer j : i) {
        System.out.print(j + " ");
    }
    System.out.println();
}

For some documentation on the ArrayList I was using, you can refer to here. As I've said again, this is a very hastily constructed bit of code, and I'm sure there are things wrong with it.

1
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
import java.util.StringTokenizer;


public class Test1 {

    /**
     * @param args
     * @throws IOException 
     */

    /*1,2,3,4,5,6
    3,4,5,6,7,8
    5,6,7,8,9,9
    1,2,3,4,5,6*/

    public static void main(String[] args) throws IOException {

        File file = new File("C:\\test.txt");
        Scanner input = new Scanner(file);
        BufferedReader bufRdr  = new BufferedReader(new FileReader(file));
        String line = null;

        int row = 0;
        int col = 0;

        while((line = bufRdr.readLine()) != null)
        {   
            while(input.hasNextLine()) {
                String tmp=input.nextLine();
                row++;
            }
            StringTokenizer st = new StringTokenizer(line,",");
            while (st.hasMoreElements()) {
                col=Integer.parseInt(st.nextToken());
            }
        }
        bufRdr.close();

        String array[][] = new String[row][col];
        BufferedReader bufReader  = new BufferedReader(new FileReader(file));
        String strLine=null;

        for(int i=0;i<row;i++){
        if((strLine=bufReader.readLine())!=null){
                StringTokenizer stringToken = null;
                stringToken = new StringTokenizer(strLine,",");

                while(stringToken.hasMoreTokens()){
                    for(int j=0;j<col;j++){
                        array[i][j]=stringToken.nextToken();    
                        System.out.println("["+i+"]"+"["+j+"]:"+array[i][j]);
                        System.out.println("******************");
                    }
                }

            }
        }
    }
}

I have made this code.Its give the number of rows,Columns and 2d-array according to your text file.

1

In first sight, this is what you want ,

StringTokenizer st = new StringTokenizer(line,",");
                                           ^

This is an infinite loop.

 while (st.hasMoreTokens()){
          i++;
        }

These are the two things that are troubling you.

0

How come you got Scanner and Reader together?

One way to do is to read in the whole file as one String, then parse the String. Do not make things complicated by using so many 'readers'.

To get the number of rows, count the number of line separators, then add one. To get the number of column of each row, use regular expression, such as "\\s+", or"\\s+,\\s+" to count the number of columns. As you are using a two dimensional array, get the maximum of these.

Don't user readLine(), it will ignore newLine.

0

Try Scanner.useDelimiter.

 String str="1,2,3,4,5,6";

 Scanner sc=new Scanner(str).useDelimiter(",");

 while(sc.hasNext())
 {
  System.out.println(sc.next());
 }

EDIT:

    File file = new File("test.txt");
    Scanner input = new Scanner(file).useDelimiter("[,\\s]");
    ArrayList<ArrayList<String>> list=new ArrayList<ArrayList<String>>();
    ArrayList<String> item=new ArrayList<String>();
    String value="";

    while(input.hasNext()){
       value=input.next();
       if("".equals(value))
         {
           list.add(item);
           item=new ArrayList<String>();
         } 
       else
         item.add(value);
     }
    list.add(item);
    for(ArrayList<String> listItem:list)
     {
        for(String str:listItem)
          System.out.print(str + " " );
        System.out.println();
      }
0

Since you said your txt file has values separated by ",", why not use split function of String Class to get the Array of String, whose length will tell you the number of columns and your while loop will tell you the number of rows.

Here is small program to illustrate what i mean, which is as follows :

import java.io.*;

public class FileRowColumn
{
    public static void main(String[] args) throws Exception
    {
        File file = new File("test.txt");
        BufferedReader br = new BufferedReader(new FileReader(file));
        int width = 0, height = 0;
        String line = "";
        while ((line = br.readLine()) != null)
        {
                    if (width == 0)
                    {
                        String[] str = line.split(",");
                        width = str.length;
                    }
            height++;
        }
        System.out.println("Row : " + height);
        System.out.println("Column : " + width);
        /*Adding values to the 2D Array here.*/
        String[][] data = new String[height][width];
        br = new BufferedReader(new FileReader(file));

        for (int i = 0; i < height; i++)
        {
            if ((line = br.readLine()) != null)
            {
                for (int j = 0; j < width; j++)
                {                                   
                    String[] str = line.split(",");     
                    data[i][j] = str[j];
                    System.out.print("Data[" + i + "][" + j + "] : " + data[i][j] + " ");
                }
            }
            System.out.println("\n");
        }
    }
}

Here is the output for your test case :

Result for Rows and Columns Hope that might help.

Regards

1
  • @BensonLeung : Your Welcome. Keep Smiling :-)
    – nIcE cOw
    Jan 12, 2012 at 17:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.