2013-04-02 198 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