大家好我正在做家庭作业,我们必须提示用户要显示的对象(矩形或三角形),然后提示用户输入对象的高度和宽度。最后我们提示用户对于从哪里开始“绘制对象”的x和y坐标 我们使用[20] [20] char数组制作一个“画布”,我们使用该数组存储并稍后显示char以便“绘制”该对象。
问题:如果我选择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;}
}
}
}
答案 0 :(得分:1)
我不确定你要做什么。但是如果你初始化你的画布阵列,你的问题就会得到解决。
在你的主要内容中尝试:
for(int i = 0; i < 20 ;i++)
for(int j = 0; j < 20 ;j++)
canvas[i][j]=' '; //or any character you like
P.S。小心你的x和y因为你可能会得到一个indexOutOfBound错误,如果你不检查宽度+ x和高度+ y是否小于20,因为你像这样声明画布:char[][]canvas = new char[20][20];
而不是动态的用户输入