gpt4 book ai didi

java - 获取 Java.io.FileNotFoundException;在程序中并且不知道如何修复

转载 作者:行者123 更新时间:2023-12-01 12:34:46 38 4
gpt4 key购买 nike

自己构建一个小游戏作为一个小项目,我不太擅长错误处理等,所以我收到了 java.io.FileNotFoundException 错误,但我没有确定如何继续。

这是我在这里发表的第一篇文章,所以我为如此含糊而道歉,我猜我需要抛出异常或以某种方式捕获它?

import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

public class GameOver extends Actor {
public static Counter highScore;
public static int currentScore;
/**
* Act - do whatever the gameOver wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public void act() {
displayScore();
if(Greenfoot.isKeyDown("space")) {
Greenfoot.setWorld(new City());
}
}
//This is where I am getting the error
private void displayScore() {
highScore = new Counter ("HIGHSCORE: ");
getWorld().addObject(highScore, 700, 50); //Add width/height
highScore.setLocation(City.WIDTH/2, City.HEIGHT/4);
currentScore = (0+City.score);
int topScore;
//The error is coming from this block of code
BufferedReader saveFile = new BufferedReader(new FileReader("TextSave.txt"));
topScore = Integer.parseInt(saveFile.readLine());
saveFile.readLine();
saveFile.close();
if (topScore < currentScore) {
FileWriter writer = new FileWriter("topScore.txt");
writer.write(currentScore);
writer.close();
}
highScore.setValue(topScore);
}
}

最佳答案

您的问题是“如何捕获异常”,这是一个答案:

    //This is where I am getting the error 
private void displayScore() {
highScore = new Counter ("HIGHSCORE: ");
getWorld().addObject(highScore, 700, 50); //Add width/height
highScore.setLocation(City.WIDTH/2, City.HEIGHT/4);
currentScore = (0+City.score);
int topScore;
try{
//The error is coming from this block of code
BufferedReader saveFile = new BufferedReader(new FileReader("TextSave.txt"));
topScore = Integer.parseInt(saveFile.readLine());
saveFile.readLine();
saveFile.close();
if (topScore < currentScore) {
FileWriter writer = new FileWriter("topScore.txt");
writer.write(currentScore);
writer.close();
}
highScore.setValue(topScore);
catch(FileNotFoundException e){
// Handle your exception here, like print a message 'the file XXX couldn't be read'
}
}

或者您可以将其传递给调用函数并在那里处理它:

private void displayScore() throws FileNotFoundException {
...
}

关于java - 获取 Java.io.FileNotFoundException;在程序中并且不知道如何修复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25687270/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com