java - 我在多维数组的特定索引处输入和显示字符时遇到问题

标签 java arrays multidimensional-array

大家好,我目前正在做一个作业,我们必须提示用户他想要显示什么对象(矩形或三角形),然后提示用户输入对象的高度和宽度。最后我们提示用户用于开始“绘制对象”的 x 和 y 坐标 我们使用 [20][20] 字符数组制作“ Canvas ”,并使用该数组存储并稍后显示该字符,以便“绘制”对象。

问题:如果我为用户选择的坐标选择 x=0 , y=0 ,则一切正常。如果我为 x 和 y 选择任何其他值,则输出全部为空白。代码如下,任何人都可以提供有关发生了什么事的提示吗?感谢您的帮助。

import java.util.*;

public class Multidimensional {

public static char[][]canvas = new char[20][20];
public static int height, width, x, y;
public static char userChar;

public static void setRectangle()
{
    Scanner kb = new Scanner(System.in);
    System.out.println("Enter height");
    height = kb.nextInt();
    System.out.println("enter Width");
    width = kb.nextInt();
    System.out.println("Enter character");
    String input = kb.next();
    userChar = input.charAt(0);

    System.out.println("Enter location on canvas (x and y coordinate)");
    x = kb.nextInt();
    y = kb.nextInt();



    //loop for the rows
    for(int row=0; row<= height-1; row++){  

        //loop for the columns

        for(int column=0;column<=width-1;column++ ){ 

            canvas[row+y][column+x] = userChar; 
            //System.out.print("ROW+Y=   "   + (row+y));
            //System.out.print("    COLUMN+X=  " + (column+x));

        }


    }

    //displaying the array (for test purposes, not in final code)
    for(int row=0 ; row< 20; row++){

        for(int column=0; column <20; column++){


            System.out.print(canvas[row][column]);
        }
        System.out.println();
    }

}


public static void main(String[] args) {
    String userChoice;
    Scanner kb =new Scanner(System.in);
    boolean userQuit = false;

    while(userQuit ==false){


    System.out.println("1. Type S to draw a rectangle.");
    System.out.println("2. Type T to draw a triangle.");
    System.out.println("3. Type D to display.");
    System.out.println("4. Type Q to quit.");
    userChoice = kb.next();

    if(userChoice.equalsIgnoreCase("s"))
    {Multidimensional.setRectangle();
        }
    else if(userChoice.equalsIgnoreCase("q"))
    {break;}

    }
}

}

最佳答案

我不确定你想做什么。但是如果你初始化你的 Canvas 数组,你的问题就会得到解决。

在你的 main 中试试这个:

for(int i = 0; i < 20 ;i++)
    for(int j = 0; j < 20 ;j++)
        canvas[i][j]=' '; //or any character you like

附:小心你的x和y,因为如果你不检查width+x和height+y是否小于20,你可能会得到一个indexOutOfBound错误,因为你像这样声明canvas: char[][]canvas = new char [20][20];并且不随用户输入动态变化

关于java - 我在多维数组的特定索引处输入和显示字符时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8162232/

相关文章:

php - Ajax 访问 PHP 以 JSON 形式返回的多维数组

java - Java 中的引用是如何工作的?

java - 为什么在 netbeans 项目中从 ant 命令行运行 test-with-groovy 不能运行测试?

java - Google Drive FileList 返回空项目

Javascript:从字符串数组创建字典

c++ - MPI_Scatter 一个二维数组在其他二维数组中

java - 我怎样才能让一个方法重复自己呢? java

arrays - 2D数组中的最大路径总和

python - NumPy 的/科学的 : why it is throwing error

java - 如何在构造函数中用随机整数填充数组? (二维数组)