日期:2014-05-20  浏览次数:20790 次

求助, 怎么判断主函数参数的中的减号
题目要求是
java -jar word-counts.jar <-a|-c> <input_filename> <output_filename>
 input_filename -- is a relative or absolute path to the input file to process,
  or '-' to indicate input should be read from stdin
 output_filename -- relative or absolute path to the output file to write the results to,
  or '-' to indicate input should written to stdout
 -a -- output words and counts ordered alphabetically by the words
 -c -- output words and counts ordered by count descending

在函数中怎么检测“-”号是否存在,“-”号如果存在的话怎么检测后面参数是a还是c

------解决方案--------------------
无论"-a"还是"-c"都是是一个字符串。参考String类。
------解决方案--------------------
public static void main(String[] args) {
String tt = "java -jar word-counts.jar -a <input_filename> <output_filename>";
if (tt.contains("-a")) {
System.err.println("aaaaa");
} else if(tt.contains("-c")){
System.err.println("ccccccccccc");
}
}


run:
aaaaa
成功生成(总时间:0 秒)
------解决方案--------------------
Java code

public class WordCount {
    public static void main(String[] args) {
        InputStream is = null;
        OutputStream os = null;
        boolean alphaOrder = true;

        if (args.length == 2 || args.length == 3) {
            int i = 0;

            if (args.length == 3) {
                if (args[0] == null) {
                    // 输出错误信息
                    return;
                }

                switch (args[i++]) {
                case "-a":
                    break;
                case "-c":
                    alphaOrder = false;
                    break;
                default:
                    // 输出错误信息
                    return;
                }
            }

            if ("-".equals(args[i]))
                is = System.in;
            else
                try {
                    is = new FileInputStream(args[i]);
                } catch (IOException ex) {
                    ex.printStackTrace();
                    return;
                }

            i++;

            if ("-".equals(args[i]))
                os = System.out;
            else
                try {
                    os = new FileOutputStream(args[i]);
                } catch (IOException ex) {
                    ex.printStackTrace();
                    return;
                }
        } else {
            // 输出错误信息
            return;
        }

        // 数据读写和单词计数部分自己可以写了吧
    }
}