【问题标题】:Command Line - FileNotFoundException命令行 - FileNotFoundException
【发布时间】:2016-11-24 09:10:56
【问题描述】:

我正在创建一个测试器。

当我尝试时

javac WordListsTester.java java WordListsTester a.txt

我认为它应该显示一条错误消息,因为文件必须是“dictionary.txt”,但它不是。

我应该解决什么问题?

public class WordListsTester {
public static Scanner input = new Scanner(System.in);

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

    WordLists scrabble = new WordLists("dictionary.txt");

    String[] containLetter = scrabble.containsLetter(3, 'a');
    output(containLetter, "containsLetter.txt");

    String[] wordsStarts = scrabble.startsWith(3, 'a');
    output(wordsStarts, "startsWith.txt");

    String[] wordLength = scrabble.lengthN(3);
    output(wordLength, "lengthN.txt");

    String[] multiLetter = scrabble.multiLetter(2, 'h');
    output(multiLetter, "multiLetter.txt");

    String[] vowelHeavy = scrabble.vowelHeavy(5, 2);
    output(vowelHeavy, "vowelHeavy.txt");

    input.close();

}

public static void output(String[] words, String fileName) {
    try {
        PrintWriter out = new PrintWriter(fileName);
        if (words.length == 0) {
            System.out.println("NO matched Words exist");
        }
        for (int i = 0; i < words.length; i++) {
            out.println(words[i]);
        }
        out.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        System.out.println("Invalid file name.");
    }
}

}

【问题讨论】:

  • 为什么文件必须是“dictionary.txt”?您将 a.txt 作为参数传递给您的程序,但您的程序没有对参数做任何事情。
  • 我的意思是,因为我必须阅读dictionary.txt,所以我希望在传递不正确的a.txt 时看到错误。
  • 然后检查 args[0] 是否等于“dictionary.txt”。但是,如果它唯一的有效值是“dictionary.txt”,那么首先传递一个参数有什么意义呢?这有点像“您可以选择汽车的颜色,但前提是您选择黑色”。
  • 你的意思是你想要if (args.length &gt; 0 &amp;&amp; !args[0].equals("dictionary.txt")) System.out.println("You typed " + args[0] + " instead of 'dictionary.txt'");
  • 如果我输入 java WordListsTester.java a.txt 不是 args[0] 吗?你对 args[0] 有什么看法?

标签: java terminal try-catch command-line-arguments filenotfoundexception


【解决方案1】:
WordLists scrabble = new WordLists(args[0]);

不确定这个程序到底做了什么。

不确定是否在 WordLists 类中检查文件名。

但是如果你想检查 USER INPUT,你需要检查 args[0]。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-05
    • 2012-07-15
    相关资源
    最近更新 更多