[英]Passing an int value from class to another and storing it in an array in Java
我的Java程序中有2個類,第一個類包含一個要獲取用戶輸入的文本字段,我試圖從一個文本字段(用戶輸入)傳遞一個int值並將此值存儲在包含的數組中在另一堂課。
第1類這是我從文本字段獲取數據的第一類
if (SubmitButton.equals(e.getSource())) {
int input = Integer.parseInt(textField1.getText());
myClass2.setAge(input );
}
第2類這是我正在嘗試將來自第1類的用戶輸入的數據存儲到數組中的類
public int setAge(int input) {
return input;
}
//this is where i am trying to store the value
int[] Age = {input};
由於某種原因,“輸入”無法解析為變量
可以幫忙一下嗎?
因為變量input
具有方法局部作用域,所以不能從方法setAge()
外部訪問它
使用input
變量作為實例成員變量
int input;
public int setAge(int input) {
this.input=input;
return input;
}
//this is where i am trying to store the value
int[] Age = {input};
在第二個類中,將數組定義為成員變量並分配值。
public class MyClass2 {
private int[] age = new int[1];
public void setAge(int input) {
age[0] = input;
}
}
我猜您想將“輸入”存儲在Class2中,然后將其放入Age數組中。 為此,您應該在類2中有一個名為“輸入”的變量(我想您的名字更喜歡是這個)。之后,您可以像這樣存儲這些數據。
private int input;
public int setAge(int input) {
this.input = input;
return input;
}
int[] Age = {input};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.