简体   繁体   中英

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

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:

static int x; 

Declare the variable outside of your method. Or if you can, put it as a parameter wherever paint is called. That is a good way to do it too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM