如何从另一个 class 指定一个 int
How to specify an int from another class
这将是一个令人尴尬的问题,但我是 Java 的新手。
我有一个 class 实现了 ActionListener
,其中包含以下代码:
public class Shop1 implements ActionListener{
public void actionPerformed(ActionEvent event){
int alis = 0;
alis++;
System.out.println(alis);
}
}
每次我按下按钮时,它都会显示 1
。我知道每次按下按钮时,它都会将整数设置为 0
,并添加 1
,但我试图将整数放在 class 之外,但这次它无法识别int
.
您在这里看到的(变量始终为 0)是由变量 scope.
引起的
在 Java 中,变量具有 块作用域 ,这意味着它们仅在创建它们的块(以及该块中的任何块)中有效. 一个简单的例子:
public void scope1(){
if (something){
int myint = 1;
// possibly some other code here...
}
System.out.println(myint); // This will not compile, myint is not known in this scope!
int myint = 1; // Declare myint in this scope
System.out.println(myint); // now it works.
}
如您所见,第一个 myint
在 if 块 scope 中声明,导致它在 if 块之外无效。 myint
的第二个定义对整个方法块有效(在创建它的行之后)。
回到您的问题:您正在创建的变量具有 actionPerformed()
方法的块作用域。因此,当该方法 returns 时,变量将不再有效,它的值将消失。当您再次进入该方法时,您会在该范围内创建一个新变量。
要按照您想要的方式处理它,请将变量 "up" 移动到比方法更高的范围。我建议在 Shop1
:
中这样做
public class Shop1 implements ActionListener{
private int alis;
public void actionPerformed(ActionEvent event){
alis++; // the variable is defined in the classes scope, so the values is "kept"
System.out.println(alis);
}
}
有什么不明白的地方欢迎评论!
这将是一个令人尴尬的问题,但我是 Java 的新手。
我有一个 class 实现了 ActionListener
,其中包含以下代码:
public class Shop1 implements ActionListener{
public void actionPerformed(ActionEvent event){
int alis = 0;
alis++;
System.out.println(alis);
}
}
每次我按下按钮时,它都会显示 1
。我知道每次按下按钮时,它都会将整数设置为 0
,并添加 1
,但我试图将整数放在 class 之外,但这次它无法识别int
.
您在这里看到的(变量始终为 0)是由变量 scope.
引起的在 Java 中,变量具有 块作用域 ,这意味着它们仅在创建它们的块(以及该块中的任何块)中有效. 一个简单的例子:
public void scope1(){
if (something){
int myint = 1;
// possibly some other code here...
}
System.out.println(myint); // This will not compile, myint is not known in this scope!
int myint = 1; // Declare myint in this scope
System.out.println(myint); // now it works.
}
如您所见,第一个 myint
在 if 块 scope 中声明,导致它在 if 块之外无效。 myint
的第二个定义对整个方法块有效(在创建它的行之后)。
回到您的问题:您正在创建的变量具有 actionPerformed()
方法的块作用域。因此,当该方法 returns 时,变量将不再有效,它的值将消失。当您再次进入该方法时,您会在该范围内创建一个新变量。
要按照您想要的方式处理它,请将变量 "up" 移动到比方法更高的范围。我建议在 Shop1
:
public class Shop1 implements ActionListener{
private int alis;
public void actionPerformed(ActionEvent event){
alis++; // the variable is defined in the classes scope, so the values is "kept"
System.out.println(alis);
}
}
有什么不明白的地方欢迎评论!