Itai Iloni Itai Iloni - 1 month ago 7
Java Question

How do you make variables made inside a method available to all other methods in a class?

I'm a coding newb and want to learn some more java. I'm currently taking an introductory programming course in high school and am just trying to play around outside of class. This program I'm creating is supposed to print out a few instructions and questions in the console, to which I want to retrieve user input using a scanner and variable. The goal of the program is for the user to be able to create a 'drawing' based on pure instinct, then this drawing is displayed after the fact.

Here's my problem. I'm asking the user and storing the information in variables that are native to the main method, but I need to use this information in the paintComponent method.

I tried adding static in front of the variable such as:

static int emptyRectW1 = kboard.nextInt();
but this just shows the error "Illegal modifier for parametic emptyRectW1; only final is permitted."

I knew it was a long shot trying that out, but that's the best I've got.

I'm using Java Eclipse as my IDE.
Thanks for any help, looks like the only way to learn is to mess up and have somebody else point out my mistake! :)

Here's the code:

import java.util.Scanner;
import java.awt.Graphics;
import java.awt.Color;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class BlindDrawing extends JPanel {
public static void main (String[] args) {
Scanner kboard = new Scanner(System.in);
System.out.println("Welcome to the Blind Drawing Game!");
System.out.println("In this game, you will be asked questions about how to construct an image using rectangles and ovals. You will be asked the shape's dimensions and position. The origin (0,0) is the top left corner.");
System.out.println("First you're making an empty rectangle, how wide do you want it to be?");
int emptyRectW1 = kboard.nextInt();
System.out.println("What about the height?");
int emptyRectH1 = kboard.nextInt();

}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawRect(0,0,emptyRectW1, emptyRectH1);
}
}

Answer

Actually, a variable declared inside a method is a local variable.

Please extend the scope of the the two variables just before your main method. See code below.

static int emptyRectW1, emptyRectH1;
public static void main (String[] args) {

Then manipulate the latter code to avoid duplicate variable declaration as shown below.

    emptyRectW1 = kboard.nextInt();
    System.out.println("What about the height?");
    emptyRectH1 = kboard.nextInt();

I hope this helps.