所以我正在尝试使用 JFrames 创建一个基本的 RPG 用户 ID 选择菜单;我选择使用单选按钮显示 ID 选项。一旦用户选择了 ID,我就使用 JOptionPane 将其打回原处。所有这些都是在 MyClass 类中完成的。当用户进行 ID 选择时,我从 .txt 文件中读取以检查用户所做的选择,因为每个 userID 都与一个 Character 相关联,该 Character 的统计信息也包含在 .txt 文件中。我能够分解 .txt 文件的多行并将所有不同的特征存储为单独的字符串。我的问题是,现在我想在 MyClass 之外创建另一个使用 JFrames 显示所述特征的类,我在传递变量时遇到了麻烦,因为 .txt 文件的分解是在 Try-Catch 内部完成的,并且基于我读过,这些变量只包含在 Try-Catch 的范围内。这就是我提到的第一个类中的方法的样子:
public void checkID()
{
StringBuilder allInfo=null; //Used to store all the Info
String line=null; //Used as condition for loop & to generate the String Builder
String strAll2=null;
String[] sa=null;
String[] sb=null;
String[] sd=null;
String[] se=null;
BufferedReader br=null;
//User Id as a string
try {
br = new BufferedReader(new FileReader("charList.txt"));
allInfo= new StringBuilder();
while ((line=br.readLine()) != null)
{
allInfo.append(line + "\n");
}
strAll2=allInfo.toString(); //all the info of charList.txt as one StringBuilder
sa=strAll2.split("\n"); //all the info of charList.txt as a String
sb=sa[0].split("\t"); //all the info of the first line of the file as individual strings
sd=sa[1].split("\t"); //all the info of the second line of the file as individual strings
se=sa[2].split("\t"); //all the info of the third line of the file as individual strings
if (firstIdButton.isSelected())
{
strId=sb[0];
}
else
{
if (secondIdButton.isSelected())
{
strId=sd[0];
}
else
{
if (thirdIdButton.isSelected())
{
strId=se[0];
}
}
}
ID = Integer.parseInt(strId);
}//end of try
catch (IOException e) {
e.printStackTrace();
}//end of catch
setVisible(false); //Hides Window
}//end of check id method
我在主类中分别将 ID 和 strId 声明为 public int 和 String 现在,我希望在 MyClass 之外的另一个类中按照调用 ID 的方式做一些事情,并可能通过几个 if-else 运行它查看要显示的字符。问题是,当我实例化构造函数并尝试访问变量时,它返回 0,因为 try-catch 的范围不允许我将其与块内获得的值一起传递。我也试图让我的方法返回 ID 的值,但我在 MyClass 之外遇到了同样的问题
这是我在实施它时遇到问题的地方
公共类 CharacterEditor {
public static void main(String[] args) throws IOException{
MyClass iw= new MyClass();
int theID=iw.ID;
System.out.println(theID);
} }