java - 将变量传递给 catch - Java

标签 java android variables try-catch

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

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

当发生这种情况时,我希望它执行的操作是将 rideCount 设置为 0 并调用设置其他所有内容的方法,但我似乎无法通过将rideCount变量添加到catch位。有人可以帮忙吗?

提前致谢。

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/

相关文章:

android - 无法在 Eclipse 中执行初始 Android Wear Hello World App

excel - 具有日期条件的自动过滤器返回空白

c# - 在 .NET 中初始化空变量

javascript - jQuery - animate() 属性

java - JDBC:简单的 MSSql 连接示例不起作用

java - Google AppEngine 数据存储 - 远程登录?

android - 命令失败,退出代码为 ENOENT

android - 使用 RxJava 和 Retrofit 链接两个 Web 服务调用

java - 为什么要使用模板引擎? jsp 包括和 jSTL 与瓦片、freemarker、velocity、sitemesh

java - 在 Java 中定义 double 文字时使用 'd' 是一个好习惯吗?