[英]Set a variable for a class from an object and access the same value from another object of that class
Here are the three classes. 这是三个类。
In this scenario, Middle.java has a static global variable x. 在这种情况下,Middle.java具有静态全局变量x。
I'm setting the value of x from the input.java class using setter method. 我正在使用setter方法从input.java类设置x的值。 and now I want to access the same value of x from the output.java using getter method.
现在我想使用getter方法从output.java访问相同的x值。 But when I try to do this, it doesn't do that.
但是,当我尝试执行此操作时,它不会执行此操作。 Here are the class files.
这是类文件。
Input.java Input.java
public class Input { public static void main(String[] args) { Middle m = new Middle(); m.setX(100); } }
2.Middle.java 2,Middle.java
public class Middle {
public static int x;
public void setX(int value)
{
x = value;
}
public int getX()
{
return x;
}
}
3. Ouput.java 3. Ouput.java
public class Output {
public static void main(String[] args) {
Middle m = new Middle();
int temp = m.getX();
System.out.print(temp);
}
}
So, when I run the input.java program first and set the value to 100 and then run the output.java program, the output I must get is 100. but I don't get that. 因此,当我先运行input.java程序并将其值设置为100,然后运行output.java程序时,我必须获得的输出为100。但是我没有得到。
As you know, values held in objects will become inaccessible after your program stops running. 如您所知,在程序停止运行后,对象中保存的值将变得不可访问。 Therefore, you need to store the value somewhere permanently so it can be read the next time you run the program.
因此,您需要将值永久存储在某个地方,以便下次运行程序时可以读取它。
One way to do this is to write the value to a file on your hard drive: 一种方法是将值写入硬盘上的文件:
try (FileWriter writer = new FileWriter("/some/path/to/a/file.txt")) {
writer.write(yourValue);
} catch (IOException e) {
e.printStackTrace();
}
And then you can read it like this: 然后您可以这样阅读:
try (FileReader reader = new FileReader("/Users/mulangsu/Desktop/temp.txt")) {
System.out.println(reader.read());
} catch (FileNotFoundException e) {
System.out.println("File not found");
} catch (IOException e) {
e.printStackTrace();
}
Another way to do this is to save your values to a web server. 另一种方法是将您的值保存到Web服务器。 This way, your value can persist over different devices.
这样,您的价值可以在不同的设备上保持不变。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.