gpt4 book ai didi

java - 将值保存在内存中并获取它

转载 作者:行者123 更新时间:2023-12-01 21:57:03 29 4
gpt4 key购买 nike

我正在开发 swing 应用程序,以下步骤解释了我的问题。

  1. I have a dialog box where I need to select the College.

  2. Once I select the department, that window will be closed with the "dispose();" method.

  3. Then one more window will pop-up, where I have to select the department based on the selected college.

现在的问题是 Collage 类的对象已被销毁,因为弹出窗口已关闭,所以我如何在 Java 中将选定的拼贴值存储在内存中。

代码示例:

public class Test
{
public static void main(String args[])
{
Sample first = new Sample();
first.setData(1);

Sample second = new Sample();
System.out.println(first.getData()); // 1
System.out.println(second.getData()); // 0
}

}


public class Sample
{
private int number;

public int getNumber()
{
return number;
}

public void setNumber(int number)
{
this.number = number;
}

public void setData(int a)
{
setNumber(a);
}

public int getData()
{
return getNumber();
}
}

我想要使用第二个对象的值1,它应该像“second.getData()”应该带来值1。是否可能,如果是,那么如何?谢谢。

最佳答案

你也可以尝试一下,

我一直是代表想法,现在你可以根据自己的需求来引领,

public class InputSelect {

public static final String[] colleges = { "College-1", "College-2", "College-3", "College-4" };

public static final String[][] dept = {{"college-1 Department-1","college-1 Department-2"},{"college-2 Department-1","college-2 Department-2"},{"college-3 Department-1","college-3 Department-2"},{"college-4 Department-1","college-4 Department-2"}};

public static void main(String[] args)
{

JFrame frame = new JFrame("Input Dialog Example 3");
String favoritecollege = (String) JOptionPane.showInputDialog(frame,
"Select Your Choice Colleges : ",
"Choose College",
JOptionPane.QUESTION_MESSAGE,
null,
colleges,
colleges[0]);

int index = 0;

for(String clg : colleges){
if(favoritecollege.equals(clg)){
break;
}else{
index++;
}
}

String favouriteDept = (String) JOptionPane.showInputDialog(frame,
"Select Your Choice Department : ",
"Choose Dept of "+ favoritecollege +" college : ",
JOptionPane.QUESTION_MESSAGE,
null,
dept[index],
dept[index][0]);

System.out.printf("Favorite College is %s.\n", favoritecollege);
System.out.printf("Favorite Dept is %s.\n", favouriteDept);


}

}

已编辑

public static void main(String args[])
{
Sample first = new Sample();
first.setData(1);
//Either
//Sample second = new Sample();
//second.setData(1);
//or
Sample second = first;

System.out.println(first.getData()); // 1
System.out.println(second.getData()); // here, you will get 1 after above changes made.
}

无论哪种方式都可以,

请确保您选择这种方式,

Sample second = first;

然后无论您在 first 上进行更改,或second 。这应该反射(reflect)在两个实例上,即 firstsecond 。因为它不是两个不同的实例。这只是一个例子。

但如果你选择这种方式,

Sample second = new Sample();
second.setData(1);

那就不一样了first ,表示您对 second 进行了任何更改那么它不应该反射(reflect) first .

所以,你可以采取任何方式,你很方便。祝你好运。

关于java - 将值保存在内存中并获取它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34130595/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com