检查是args [0]不包含任何元素?

时间:2015-04-05 16:28:14

标签: java

我正在编写的程序中有一个'Usage'方法,如果args [0]什么都不包含,它会被调用。这是程序,当我尝试某种类型的东西,如(args [0] .isEmpty()...)我得到一个ArrayIndexOutOfBounds。

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;


public class Desk {

public static void main(String[] args) throws FileNotFoundException {   
    if(args[0].isEmpty()){
        Usuage();
    }

    try{
        count(new TreeSet<String>(),  new File("C:\\Users\\Ceri\\workspace1\\Cw2Task2\\src\\" + args[0]));
    }catch(FileNotFoundException e){
        System.out.println("Error: File not found");
    }

}

private static void count(TreeSet<String> treeSet, File file) throws FileNotFoundException {
    // TODO Auto-generated method stub
    Scanner in = new Scanner(file);

    while(in.hasNext()){
        String temp = in.next();
        treeSet.add(temp);
    }

    System.out.println("There are " +  treeSet.size() + "Unique words in the text file ");  
}

private static void Usuage(){
        System.out.println("Not entered");
}

}

1 个答案:

答案 0 :(得分:3)

你应该检查:

if(args.length < 1) {