gpt4 book ai didi

java - 将变量传递给 catch - Java

转载 作者:太空狗 更新时间:2023-10-29 16:33:21 25 4
gpt4 key购买 nike

我正在 Android Studio 中制作一个应用程序,它可以让你跟踪你坐过山车的次数,并计算出你经历了多少 g 力等。

我希望 rideCount 变量在退出时保存,所以我将其写入文件。然后当该 Activity 开始时,它将读取该文件并将其放入 rideCount 变量中。因为它在退出时写入,所以文件中一开始没有任何内容。

发生这种情况时我希望它做的是将 rideCount 设置为 0 并调用设置其他所有内容的方法,但我似乎无法通过rideCount 变量到捕获位。谁能帮忙?

提前致谢。

File file = new File("AltonAirCount.txt");

try{
Scanner input = new Scanner(file);
int rideCountFile = input.nextInt();
final int[] rideCount = {rideCountFile};
onCreate2(rideCount);
} catch (FileNotFoundException ex){
//I want it to set rideCount to 0 here
//I want it to call up onCreate2 and pass rideCount to it
}}

.

    public void onBackPressed(int[] rideCount, File file) {

try {
PrintWriter output = new PrintWriter(file);
output.println(rideCount);
output.close();

} catch (IOException ex) {


}
}

最佳答案

rideCountFile 必须在 try block 之前声明,以便 catch block 可以访问。

int rideCountFile;
try{
Scanner input = new Scanner(file);
rideCountFile = input.nextInt();
final int[] rideCount = {rideCountFile};
onCreate2(rideCount);
} catch (FileNotFoundException ex){
rideCountFile = 0;
// call onCreate2 again if you wish
final int[] rideCount = {rideCountFile};
onCreate2(rideCount);
}

当然,除非你需要在后面的一些你没有包含的代码中使用rideCountFile,否则你根本不需要在catch block 中使用它,所以代码可以简化为:

try{
Scanner input = new Scanner(file);
int rideCountFile = input.nextInt();
final int[] rideCount = {rideCountFile};
onCreate2(rideCount);
} catch (FileNotFoundException ex){
onCreate2(new int[] {0});
}

关于java - 将变量传递给 catch - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34380284/

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