如何在java中使用Scanner来计算输入.text文件中用“,”分隔的单词数?

时间:2012-01-12 03:52:21

标签: java

我的输入文件如下所示:

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

我想计算一列中的字数和行数,以便我可以知道数组大小并将它们放入2D数组中。

如何获取列数和行数? 感谢!!!!

我的代码:

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

7 个答案:

答案 0 :(得分:2)

我喜欢简短的答案。 ;)这将读取文本,删除空格并从文本中构建int[][]

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)

乍一看,这就是你想要的,

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

这是一个无限循环。

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

这两件事令你不安。

答案 2 :(得分:1)

好的,首先,您当然可以使用动态数据结构吗?我假设你事先不知道你要阅读多少列或行。这意味着你不知道如何制作阵列,除非你想通过数据进行一次冗余解析。如果您使用动态数据结构,那将不会有问题。

Java中常用的大多数动态数据结构都位于the Collections package

这将使您的任务更容易。我已经尝试为您提出的问题编写示例解决方案。 它实际上并不是很好的代码,而且我现在正在工作,所以我把它拼凑得很匆匆。请问是否有一些没有意义的事情。

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

有关我正在使用的ArrayList的一些文档,您可以参考here。正如我再次说过的,这是一个非常仓促构造的代码,我确信它有问题。

答案 3 :(得分: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("******************");
                    }
                }

            }
        }
    }
}

我已经制作了这个代码。它根据你的文本文件给出行数,列数和2d数组。

答案 4 :(得分:0)

你怎么把Scanner和Reader放在一起?

一种方法是将整个文件作为一个String读入,然后解析String。不要因为使用这么多“读者”而使事情变得复杂。

要获取行数,请计算行分隔符的数量,然后添加一行。 要获取每行的列数,请使用正则表达式,例如“\\ s +”或“\\ s +,\\ s +”来计算列数。当您使用二维数组时,请获取最大值。

不要使用readLine(),它会忽略newLine。

答案 5 :(得分:0)

尝试Scanner.useDelimiter

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

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

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

编辑:

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

答案 6 :(得分:0)

由于你说你的txt文件的值用“,”分隔,为什么不使用String Class的split函数来获取String的数组,其长度将告诉你列数,你的while循环将告诉你数字行。

这是一个小程序来说明我的意思,具体如下:

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

以下是测试用例的输出:

Result for Rows and Columns 希望这可能有所帮助。

此致