总结文本文档中的数字列表

时间:2016-04-01 22:58:50

标签: java command-line-arguments

目标是创建一个程序,该程序使用数字列表扫描文档并对数字列表求和。该程序采用两个命令行参数。第一个参数表示要求总和的行数。第二个参数告诉读取哪一行。例如,如果args [1] = 2,则告诉您每隔一行读取一次。或者如果args [1] = 3,则告诉您每三行读一次。 到目前为止,这是我的代码:

import java.util.Scanner;

import java.io.*;

public class Lab8{  

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

        int intCount = 0;

        int sum=0;  

        File myFile;

        myFile=new File("nums.txt");

        Scanner in=new Scanner(myFile);

        if (args.length!=2){

            System.out.println("ERROR:NEEDS TWO CLA'S");

        }else{
            for(int i=0;i<Integer.parseInt(args[0]);i++){
                int x=in.nextInt();
                sum=sum+x;
            }

        }
            System.out.println(sum);        


    }

我收到以下错误消息:

Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at Lab8.main(Lab8.java:33)

如何修复我的代码?谢谢!

3 个答案:

答案 0 :(得分:0)

您需要使用

检查扫描仪是否有任何内容需要阅读
Scanner.hasNextInt()
在您阅读之前

otherwise it will throw the exception you're seeing

对于“读取每一行X行”,你必须创建一个循环,在读取你想要存储的行之前读取你要跳过的行数。

答案 1 :(得分:0)

让我知道如果这实现了你想要的: *请注意,如果您的文本文件与您的程序位于同一目录中,则需要列出完整的文件路径

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


         int lineCount = Integer.parseInt(args[0]);
         int skipCount = Integer.parseInt(args[1]);

        int locaCount = 0;
        int sum=0;  
        File myFile;


        myFile=new File("nums.txt");

        Scanner in=new Scanner(myFile);

        if (args.length!=2){

            System.out.println("ERROR:NEEDS TWO CLA'S");

        }else{
            for(int i=0;i<lineCount; i += skipCount){
                int x=in.nextLine();
                sum+= x;
            }

        }
            System.out.println(sum);        


    }

答案 2 :(得分:0)

像这样(我没有测试解决方案)

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

    // Check number of parameters at the begening
    // it is not needed to open file if there is no appropriate number of parameters
    if (args.length != 2) {
        System.out.println("ERROR: Need two parameters");
        return; // Or System.exit(1);
    }

    File myFile = new File("nums.txt");
    Scanner in = new Scanner(myFile);

    int totalLines = Integer.parseInt(args[0]);
    int skipLines = Integer.parseInt(args[0]);
    int currentLine = 0;
    int sum = 0;

    while (in.hasNext() && currentLine < totalLines) {
        int num = in.nextInt();
        if (currentLine % skipLines == 0) {
            sum += num;
        }
    }

    System.out.println(sum);
}