【问题标题】:How to copy a line from a text file and print the line and line number如何从文本文件中复制一行并打印行和行号
【发布时间】:2014-09-17 03:22:18
【问题描述】:

我在编写一个程序时遇到了麻烦,该程序会在文本文件中找到错误并打印错误所在的行并打印错误所在的行号。它正在寻找的错误是每行是否有 6 个单词/数字,如果没有则会出现错误

例如:

文本文件

命名品种月日年重

命名品种月份

命名品种月日年重

***文件中的错误行:

命名品种月份 第 2 行出错:字段数应为 6,而不是 3。*

int numline= 0;
while(sc.hasNextLine())
    {

    // read a line from the input file via sc into line
        line = sc.nextLine();




        try{
        StringTokenizer stk = new StringTokenizer(line);
        String name = stk.nextToken();
        String breed = stk.nextToken();
        int month = Integer.parseInt(stk.nextToken());
        int day = Integer.parseInt(stk.nextToken());
        int year = Integer.parseInt(stk.nextToken());
        double weight = Double.parseDouble(stk.nextToken());
        numline++;
        Dog list = new Dog(name, breed, month, day, year, weight);


        dogs.add(list);




        }

        catch(Exception missError)
        {
            System.out.println("Error Lines detected in file:");
            System.out.println("Number of fields on line must be 6");

        }

    }
     // close the file
sc.close();
  System.out.println(numline);

【问题讨论】:

  • numLine++ 作为try 块中的第一行并在catch 块中使用它。

标签: java string exception int stringtokenizer


【解决方案1】:

numLine++ 作为try 块中的第一行并在catch 块中使用它。也可以使用返回String[]line.split("\\s+");,这样您就可以事先知道字段的数量,然后您就不需要依赖Exception

int numLine= 0;
while(sc.hasNextLine())
    {

        line = sc.nextLine();
        numLine++
        String[] fields = line.split("\\s+");
        if(fields.length != 6) {
           System.out.println("Error Line number:"+numLine);
           System.out.println("Number of fields on line must be 6, but it has :"+ fields.length);
        }
     }

【讨论】:

  • 谢谢,我将如何打印行和行号。
  • 计算每行的字符数,而不是单词数。
  • 这是结果:错误行号:1 行的字段数必须是 6,但它有:27
猜你喜欢
  • 2014-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-29
  • 2018-03-06
  • 1970-01-01
  • 2021-08-21
  • 2022-12-17
相关资源
最近更新 更多