簡體   English   中英

將數組作為參數傳遞時出錯 - Java

[英]Error passing array as parameter - Java

我正在修改的程序應該使用繪圖面板從中心開始向左或向右隨機移動一個正方形,並使用數組來計算它在正方形停留在屏幕上時移動到的位置(面板為 400 x 400 並且正方形是 10 x 10,所以它只能移動到 40 個可能的位置)在正方形離開屏幕后,我必須打印一個直方圖,顯示正方形移動到該索引的次數(即,如果正方形從 x 坐標 200 移動到 190,索引 19 將得到一個計數)這是我的代碼:

import java.awt.*;
import java.util.*;

public class RandomWalkCountSteps {
// DrawingPanel will have dimensions HEIGHT by WIDTH
public static final int HEIGHT = 100;
public static final int WIDTH = 400;

public static final int CENTER_X = WIDTH / 2;
public static final int CENTER_Y = HEIGHT / 2;

public static final int CURSOR_DIM = 10;

public static final int SLEEP_TIME = 25; // milliseconds

public static void main( String[] args ) {
    DrawingPanel panel = new DrawingPanel( WIDTH, HEIGHT );

    Random rand = new Random();

    walkRandomly( panel, rand );


}

public static void walkRandomly( DrawingPanel panel, Random rand ) {
    Graphics g = panel.getGraphics();
    int[] positionCounts = new int[ WIDTH / CURSOR_DIM ];
    // start in center of panel
    int x = CENTER_X;
    int y = CENTER_Y;

    // Draw the cursor in BLACK
        g.fillRect(x, y, CURSOR_DIM, CURSOR_DIM);

    // randomly step left, right, up, or down
    while ( onScreen( x, y ) ) {

        panel.sleep( SLEEP_TIME );
        // Show a shadow version of the cursor
        g.setColor(Color.GRAY);
        g.fillRect(x, y, CURSOR_DIM, CURSOR_DIM);

        if ( rand.nextBoolean() ) { // go left
                x -= CURSOR_DIM;
        }
        else {  // go right
            x += CURSOR_DIM;
        }
        positionCounts[ x / CURSOR_DIM ]++;
        histogram(positionCounts, x, y);
        // draw the cursor at its new location
        g.setColor(Color.BLACK);
        g.fillRect(x, y, CURSOR_DIM, CURSOR_DIM);
    }
}

public static boolean onScreen( int x, int y ) {
    return 0 <= x && x < WIDTH
        && 0 <= y && y < HEIGHT;
}

   public static void histogram(int[] positionCounts, int x, int y) {
      if (onScreen(x, y) == false) {
         for (int i = 0; i < WIDTH / CURSOR_DIM; i++) {
            System.out.print(i + ": ");
            for (int j = 1; j <= positionCounts[i]; j++) {
               System.out.print("*");
            }
            System.out.println();
         }
      }
   }
}

我的問題是我找不到初始化數組的好地方,因此每次將 x 坐標傳遞給直方圖方法時它都不會重新初始化。 現在我認為我把它放在了正確的位置,我在方法 walkRandomly 中對直方圖的兩次調用中都收到此錯誤消息“錯誤:RandomWalkCountSteps 類中的方法直方圖不能應用於給定類型;” 我對 Java 和一般編程還很陌生,所以我可能缺少一些關於數組作為參數的東西。 提前致謝。

histogram有兩個參數, positionCounts類型的int[]x型的int walkRandomly ,您調用histogram兩次:一次使用int[]類型的參數positionCounts ,一次使用int類型的參數x 這就是為什么編譯器抱怨該方法“不能應用於給定類型”:方法histogram(int[], int)不能應用於(調用)給定類型,即histogram(int[])histogram(int)

我不確定你想用這段代碼做什么,但我猜你想刪除第一個調用並將第二個調用(在 while 循環內)更改為histogram(positionCounts, x)

(你已經編輯了你的代碼,所以我的回答沒有多大意義。)

暫無
暫無

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

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