2013-04-02 140 views
0

我一直在尝试自己的事情,现在我的第二个Java课程已经完成。回想起开始并记住如何使用过去几个月中学到的所有知识都很困难,所以我试图制作一个程序,询问用户他们想要绘制的形状(基于用for循环,这基本上是我在编程中学到的第一件事情),并将形状的大小定义为int。扫描仪输入存储和使用

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

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. 
    } 

} 

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

回答

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(); 
    } 
+0

不能相信我没有尝试过。非常感谢! – floatfil

1

可以将大小变量传递给绘画方法是这样的:

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. 
    } 

} 
+0

+1好主意! .. – MadProgrammer