所以我試圖用JFrame創建一個基本的RPG用戶ID選擇菜單;我選擇使用單選按鈕顯示ID選項。一旦用戶選擇並使用JOptionPane將其打回。所有這些都在MyClass類中完成。當用戶進行ID選擇時,我從.txt文件中讀取,以檢查用戶所做的選擇,因爲每個用戶ID都與一個字符相關聯,該字符的統計信息也包含在.txt文件中。我能夠分割.txt文件的多行,並將所有不同的特徵存儲爲單獨的字符串。我的問題是,現在我想創建MyClass之外的另一個類,它使用JFrame顯示所述特性,因爲在.txt文件的分解在Try-Catch內完成並且基於I已閱讀,這些變量只包含在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公共int和字符串,分別在現在的主類,我希望做什麼沿着MyClass之外的另一個類中的調用ID的行,並且可能通過幾個if-elses來運行它,以查看要顯示哪個字符。問題是,當我實例化構造函數並嘗試訪問該變量時,它返回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);
} }
我不是很理解你的問題是什麼。你真的嘗試過嗎?獲取任何錯誤? – Breavyn
如果您需要註解右括號,那麼您的塊的_far_太長。 –
Colin-I添加了更多代碼來顯示問題出在哪裏。我曾嘗試過這樣做,但沒有得到任何運行時錯誤,但是我在MyClass中爲ID獲取的值與CharacterEditor中獲得的ID的值不匹配;我在CharacterEditor中得到一個'0',這意味着當我這樣稱呼它時,它不能初始化它。 – Marco