English 中文(简体)
如何利用Khanner in java来计算用“、”从投入文件中得出的“字数?
原标题:How to use Scanner in java to count the number of words seperate by "," from a input .txt file?
  • 时间:2012-01-12 03:52:20
  •  标签:
  • 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阵列。

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

我的法典:

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);
问题回答

我喜欢缩短回答。 案文中删除了空间,并在案文中添加了<条码>。

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()][]);

奥凯,首先,你肯定能够使用动态数据结构? 我假定,你没有事先知道有多少栏或行文读。 这就是说,除非你想通过你的数据做一个多余的 par子,否则你不知道如何大打你。 如果你使用动态数据结构,那就是一个问题。

Java通常使用的多数动态数据结构位于

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.

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

            }
        }
    }
}

我制定了这一法典。 根据你的文本档案,它提供浏览量、Columns和2d-array。

首先是你们想要的,

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

这是无限的 lo。

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

这些都是困扰你们的两个问题。

你们如何走到斯堪纳和阅读器上来?

一种做法是,在整篇档案中读作一则,然后打平强。 使用这么多读者不会使事情复杂化。

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.

从用户读取,它将忽视新的Line。

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

既然你说你的笔记有“、”分离的价值观,那么,为什么不使用“平级”的分级功能来获取“强令”,其长度将告诉你栏目和你,而坐机将告诉你行数。

这里是说明意思的小型方案,内容如下:

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

这里是你试验案例的产出:

Result for Rows and Columns Hope that might help.

关于





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签