简体   繁体   English

如何在重新加载类后保留变量值

[英]How to keep variable value after reloading class

Hello I wrote a program that simulates a java quiz. 你好我写了一个模拟java测验的程序。 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. 该程序有3个嵌套类,第一类要求提供用户信息(名称id#etc),所有提供的第二个类被称为此类是当用户回答所有问题或时间用完时测验结束的实际测验这一点,第三课得分测验。 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. 当选择try again选项时,跟踪尝试的变量由一个实现。 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. 然而,问题在于跟踪用户已经尝试了多少尝试的变量被擦除了,因为我编写代码的方式程序从类1开始,然后是类2和类3,并且由于某种原因当类重新加载第二次时,变量返回到其初始值。 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. 检查FileOutputStreamFileInputStream以读取和写入文件。 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. 作为学术解决方案,您可以将value移至课程级别。

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. 这种方式value成员属于类而不是实例。

But do NOT do it in a real life application. 这样做在实际生活中的应用。 Re-consider your design. 重新考虑你的设计。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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