简体   繁体   中英

how to retrieve variable from main into a new class

im trying to use the variable "box" that i have the user set in the two following classes.the program prints out a row of boxes. the amount of boxes is determined by the user. would also like some input to see if i am doing this right. or if there is a better solution to the problem.

+------+  
|      |  
|      |   
+------+   

import java.util.*;

public class project1 {
 public static final Scanner CONSOLE = new Scanner(System.in);
  public static void main(String[] args) {
  System.out.println("Project  1 written by Mario Torres");
  int box;
  int count;
  System.out.println("Enter Number Of Box:");
    box = CONSOLE.nextInt();
  System.out.println(" the amount of boxs is" +box);
    for (count=1; count>0;count=(count-box)){
      System.out.print("+");
      topAndBottom( );
      System.out.print("|" );
      virticalLine( );
      System.out.print("|");
      virticalLine( );
      System.out.print("+");
      topAndBottom( );
    }

    System.out.println();
}
    public static void topAndBottom( ){
    for (int count=1; count <=box; count++){
      System.out.print("------+");
    }
    System.out.println();
    }
    public static void virticalLine( ){
    for (int count=1; count<=box; count++){
      System.out.print("      |");
    }
    System.out.println();
    }
}

You have declared you variable inside your main method, so you cannot access it from outside of that scope. You can take the box as parameter in your methods:

public static void topAndBottom(int box){}

Then call the method like this:

topAndBottom(box);

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