Zak*_*ley 2 java variables android try-catch
我在Android Studio中制作了一个应用程序,可以让你跟踪你曾经乘坐过山车的次数,并计算出你经历了多少次力量等等.
我希望rideCount变量在退出时保存,所以我让它写入文件.然后,当该活动开始时,它将读取该文件并将其放入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
}}
Run Code Online (Sandbox Code Playgroud)
.
public void onBackPressed(int[] rideCount, File file) {
try {
PrintWriter output = new PrintWriter(file);
output.println(rideCount);
output.close();
} catch (IOException ex) {
}
}
Run Code Online (Sandbox Code Playgroud)
rideCountFile 必须在try块之前声明才能被catch块访问.
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);
}
Run Code Online (Sandbox Code Playgroud)
当然,除非你需要rideCountFile在后面的代码中使用你没有包含的内容,否则你在catch块中根本不需要它,所以代码可以简化为:
try{
Scanner input = new Scanner(file);
int rideCountFile = input.nextInt();
final int[] rideCount = {rideCountFile};
onCreate2(rideCount);
} catch (FileNotFoundException ex){
onCreate2(new int[] {0});
}
Run Code Online (Sandbox Code Playgroud)