![](/img/trans.png)
[英]How to use a variable defined inside a method use outside the method in another method on the same Class in java
[英]How to access a variable defined in another method (In java)?
因此,我有一个在其他方法中定义的变量,我想知道如何在另一个方法中访问它? 这是我的代码:
import java.applet.Applet;
import java.awt.*;
import java.awt.Graphics;
import java.util.Scanner;
public class ProjectMain extends ProjectMethods {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int x;
System.out.println("1 for displacement, 2 for acceleration, 3 for initial velocity, 4 for final velocity, 5 for time");
x = input.nextInt();
}
public void paint (Graphics page) //Runs the applet
{
final int MID = 150;
final int TOP = 50;
setBackground (Color.WHITE);
page.drawLine (60, 60, 750, 60); //Line
if ( x = "5");
page.drawString("X discplacement = " , 30, 30);
}
}
我希望能够在第二种方法paint中添加变量“ X”,谢谢:D
您无法访问在其他方法中定义的变量。 但是,您可以在方法之外定义它。
将x
移出main
方法并使其静态:
static int x;
在方法之外声明变量。 或者,如果可以的话,将其作为参数在调用paint的任何地方放置。 这也是一个很好的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.