【问题标题】:Why am I receiving a runtime error when I have a file created?为什么我在创建文件时收到运行时错误?
【发布时间】:2026-02-19 19:10:02
【问题描述】:

下面是我在名为 GNU/Emacs 的文本编辑器中为大学课程创建的代码。这是一个初学者级别的 Java 类。这是我的问题。我没有遇到此代码的任何编译错误。但是,当我尝试执行它时,出现以下错误: Runtime Error Description

我将实际的 txt 文件保存在 class 和 java 文件所在的同一文件夹中。我不知道为什么我仍然无法编译。请指教。我应该把它放在不同的文件夹中吗?

import java.util*; import java.io.*; import java.lang.object;

public class bowling7 {

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

        Scanner bowling = new Scanner(new FileReader("bowling7.txt"));
        String[] TeamBlue = new String[10];
        String[] TeamWhite = new String[10];
        int[] TBScore = new int[10];
        int[] TWScore = new int[10];
        int TotalBlue = 0;
        int TotalWhite = 0;
        int counter = 0;
        String intro = "This program displays the team, members, and score of the winning team."
            System.out.println(intro);

        while(bowling.hasNextLine() == true){

            for(int counter = 0; counter < 11; ++counter){
                if (bowling.findInLine("Blue").equals("Blue")){

                    TeamBlue [counter] = bowling.next();
                    TBScore [counter] = bowling.nextInt();
                    TotalWhite = TotalWhite + TBScore [counter];

                }
                else {

                    TeamWhite [counter] = bowling.next();
                    TWScore [counter] = bowling.nextInt();
                    TotalBlue = TotalBlue + TWScore [counter];
                }
            }
        }

        if (TotalBlue>TotalWhite) {
            System.out.println("Team Blue");
            System.out.println(TeamBlue);
            System.out.println(TotalBlue);
            else {
                System.out.println("Team White");
                System.out.println(TeamWhite);
                System.out.println(TotalWhite);
            }
        }
    }
}

【问题讨论】:

  • 抱歉格式化
  • 请将异常堆栈跟踪作为代码格式的文本发布在您的问题中。不要使用屏幕截图。
  • 首先,请编辑您的问题,以文本形式发布错误。二、程序根据错误找不到你的文件。 Bowling7.txt 在哪里?
  • 道歉。我修复了错误。我输入了错误的文件名

标签: java runtime-error java.util.scanner filenotfoundexception


【解决方案1】:

错误信息很明确:'bowling7.txt' 不存在。

Java 将相对路径解析到 java 进程的“当前工作目录”,通常与您执行“java”命令运行此类时所在的工作目录相同。

您可以使用以下代码行检查它是什么:

System.out.println(System.getProperty("user.dir"));

注意:单独通知; import java.lang.object; 是编译时错误,因为Object 是用大写字母书写的;与java.lang 包中的所有类一样,默认导入;您应该完全删除该部分。

NB2:Java 约定是 ClassNamesAreLikeSo、fieldsAndVariablesAndParametersLikeSo;正如他们所说,在罗马时...

【讨论】:

  • 好吧,所以我意识到我在代码中输入了错误的文件名嘿嘿。这样就解决了这个错误。但是发生了另一个错误:输入不匹配异常。想法?
  • 停止使用 findInLine;试试 .next()。你应该问一个新的 SO 问题,否则这会变得非常混乱。
最近更新 更多