简体   繁体   中英

How to keep variable value after reloading class

Hello I wrote a program that simulates a java quiz. the program has 3 nested classes first class asks for the user information(name id# etc) after all is provided a second class is called this class is the actual quiz the quiz ends when the user answers all the question or the time runs out at that point the third class scores the quiz. If the user fails he can press a button that allow him to take the quiz one more time. when the try again choice is selected a variable that keep track of tries is implemented by one. However, the problem is that the variable that keeps track of how many tries the user has taken gets wiped because the way i wrote the code the program starts all the way back from class 1 , then class 2 and class 3 and for some reason that variable goes back to its initial value when the class reloads the second time. Is there a way i can save the variable so it does not get wiped? Any help will be much appreciated.

我建议在文件中写入值,以便在重新加载类时,它将从那里读取。

You should have some kind of persistence on disk for your quiz information. Check for FileOutputStream and FileInputStream to read and write to a file. There's plenty of tutorials if you google it (such as this one .)

I assume you have something like that

public class A {    
    Object value;
    public void setValue(Object value) {
       this.value = value;
    }
    public Object getValue() {
       return value;
    }
}

So when you destroy an instance and create a new one, the value is gone.

As an academic solution you can move the value to the class level.

So it would be:

public class A {    
    static final Object[] values;
    static void setValue(Object value) {
       values[0] = value;
    }
    static Object getValue() {
       return values[0];
    }
}

This way value member belong to the class rather than an instance.

But do NOT do it in a real life application. Re-consider your design.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM