[英]How to access a variable defined in another method (In java)?
So, I have a variable that I defined in another method and I was wondering how I can access it in another method? 因此,我有一个在其他方法中定义的变量,我想知道如何在另一个方法中访问它? Here's my code:
这是我的代码:
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);
}
}
I want to be able to accession the variable "X" in the second method, paint, Thanks :D 我希望能够在第二种方法paint中添加变量“ X”,谢谢:D
You can't access a variable defined in another method. 您无法访问在其他方法中定义的变量。 You can however define it outside of methods.
但是,您可以在方法之外定义它。
Move x
outside of your main
method and make it static: 将
x
移出main
方法并使其静态:
static int x;
Declare the variable outside of your method. 在方法之外声明变量。 Or if you can, put it as a parameter wherever paint is called.
或者,如果可以的话,将其作为参数在调用paint的任何地方放置。 That is a good way to do it too.
这也是一个很好的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.