【问题标题】:It says Process Finished but there is no output它说 Process Finished 但没有输出
【发布时间】:2021-11-05 17:26:29
【问题描述】:

我是 java 新手,我的代码有点问题。没有错误等,它只是一直说进程完成但没有显示输出。我检查过的文件名是正确的。

导入 java.nio.file.; 导入 java.io.;

public class GuessingGame {
    public GuessingGame() {
        String filename = "C:\\Users\\angela\\Documents\\words.txt";
        Path path = Paths.get(filename.toString());
        
        try {
            InputStream input = Files.newInputStream(path);
            BufferedReader read = new BufferedReader(new InputStreamReader(input));
            
            String word = null;
            while((word = read.readLine()) !=null) {
                System.out.println(word);
            }
        }
        catch(IOException ex) {
            
        }
    }
    public static void main (String[] args) {
        new GuessingGame();
    }
}

【问题讨论】:

  • 不要错过这个例外。请打印以确认是否发生异常。
  • 知道了,谢谢

标签: java process


【解决方案1】:

您忽略了异常并且没有关闭文件。通过使用内置的input.transferTo() 将文件复制到System.out 来节省一些输入,并通过将throws IOException 添加到构造函数和main 将异常传递给调用者处理。

用这个try-with-resources替换你的try-catch块,它处理使用后关闭文件:

try (InputStream input = Files.newInputStream(path)) {
    input.transferTo(System.out) ;
}

【讨论】:

    【解决方案2】:

    您设法调用了预期的类,但您还需要指定您在函数中声明的特定函数。像这样: public static void main (String[] args) { GuessingGame gg = new GuessingGame; gg.GuessingGame(); }

    【讨论】:

    • new GuessingGame(); 是正确的,因为它是构造函数,您的建议不会编译。
    • gg.GuessingGame() 不正确。 GuessingGame() 是构造函数,而不是方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-25
    • 1970-01-01
    • 2015-10-16
    • 1970-01-01
    • 1970-01-01
    • 2017-03-26
    • 2020-10-06
    相关资源
    最近更新 更多