繁体   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