0

既然我的第二门 Java 课程已经完成,我就一直在自己尝试。回到开始并记住如何使用过去几个月学到的所有东西是很困难的,所以我正在尝试制作一个程序来询问用户他们想要绘制什么形状(基于用for 循环,这基本上是我在编程中学到的第一件事),以及形状的大小为 int。

我已经设置了扫描仪,但我不记得大小变量必须如何/在哪里才能在我的“绘图”方法中使用它。基本上,我尝试过不同的东西,但“大小”总是遥不可及。到目前为止,这是我的代码(我已经排除了实际绘制形状的代码,但它们都涉及以 int 大小作为变量的 for 循环):

public class Practice {


 public static void main(String[] args) {

     Scanner input = new Scanner(System.in);

     System.out.println("Choose a shape!");

     String shape = input.nextLine();

     System.out.println("Choose a size!");

     int size = input.nextInt();

 }


     public static void drawCirlce() {


        //Code to draw a circle of size given input into scanner.  
     }

     public static void drawSquare() {


         //Code to draw a square of size given input into scanner.
     }

     public static void drawTriangle() {


        //Code to draw a triangle of size given input into scanner.
     }

     public static void drawRocket() {


        //Code to draw a rocket of size given input into scanner.
     }

}

非常感谢大家!我会继续环顾四周,但非常欢迎任何提示。

4

2 回答 2

1

您可以将 size 变量传递给绘图方法,如下所示:

public class Practice {
 public static void main(String[] args) {
     Scanner input = new Scanner(System.in);
     System.out.println("Choose a shape!");
     String shape = input.nextLine();
     System.out.println("Choose a size!");
     int size = input.nextInt();


     // Choose what shape you want to draw
     drawCircle(size);
     // or
     drawSquare(size);
     // or
     drawTriangle(size);
     // etc...
 }


     public static void drawCirlce(int size) {
        //Code to draw a circle of size given input into scanner.  
     }
     public static void drawSquare(int size) {
         //Code to draw a square of size given input into scanner.
     }
     public static void drawTriangle(int size) {
        //Code to draw a triangle of size given input into scanner.
     }
     public static void drawRocket(int size) {
        //Code to draw a rocket of size given input into scanner.
     }

}
于 2013-04-02T04:00:39.397 回答
0

您需要在类级别声明变量。此外,因为您使用所有方法,所以这些变量也static需要声明static

public class Practice {

    private static String shape;
    private static int size;

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Choose a shape!");
        shape = input.nextLine();
        System.out.println("Choose a size!");
        size = input.nextInt();
    }
于 2013-04-02T03:57:15.320 回答