簡體   English   中英

掃描儀輸入的存儲和使用

[英]Scanner input storing and using

現在,我的第二個Java課程已經完成,我一直在自己嘗試一些事情。 回想起過去幾個月來學到的所有東西時,很難回頭,所以我正在嘗試制作一個程序,詢問用戶要繪制什么形狀(基於用for循環,這基本上是我在編程中學到的第一件事),並且將形狀的大小作為整數。

我已經設置了掃描儀,但是我不記得要在我的“ draw”方法中使用size變量的方式/位置。 基本上,我嘗試了不同的方法,但是“大小”總是遙不可及。 到目前為止,這是我的代碼(我已經排除了實際繪制形狀的代碼,但是它們都涉及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.
     }

}

非常感謝大家! 我會四處張望,但任何提示都非常歡迎。

您可以像這樣將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.
     }

}

您需要在類級別聲明變量。 另外,由於您使用的是所有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();
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM