0

到目前为止,这是我的代码,它在大多数情况下都有效,但是,它只显示零。我无法弄清楚如何让它显示星号,因为这是我知道如何让它显示内部有东西的二维数组的唯一方法。

 import java.util.Scanner;

 public class Main {

 public static void main(String[] args) {

    int length = 0;
    int width = 0;

    Scanner input = new Scanner(System.in);

    //ask user input of array numbers
    while (length <= 20 || width <= 20) {
        System.out.print("Enter the length: ");
        length = input.nextInt();
        System.out.print("Enter the Width: ");
        width = input.nextInt();
        int[][] myarray = new int[width][length]; //To print all elements in this array  of ints,
        //loops is used to make it shorter and efficient
        for (int w = 0; w < length; w++) {
            for (int l = 0; l < width; l++) {
                System.out.print(" " + myarray[l][w]);//prints it in grid fashion
            }
            System.out.println("");
        }
    }
 }
 }
4

4 回答 4

1

在这一行,您打印出 int[][] 数组的内容,即 0。

System.out.print(" " + myarray[l][w]);//prints it in grid fashion

您可以将该部分更改为星号以使其打印星号。

于 2013-03-10T01:55:48.797 回答
0

如果您希望您的2D数组实际保存星号字符,则必须更改数组的类型以保存char值并执行以下操作:

char[][] myarray = new char[width][length]; 
for (int i=0; i < myarray.length; i++) {
   Arrays.fill(myarray[i], '*');
}
于 2013-03-10T02:00:26.890 回答
0

您不需要使用任何数组。除非这是稍后将数组用于其他用途的程序的一部分,否则您可以打印星号一定次数。

import java.util.Scanner;

public class Main {

public static void main(String[] args) {

    int length = 0;
    int width = 0;

    Scanner input = new Scanner(System.in);


    while (length <= 20 || width <= 20) {
        System.out.print("Enter the length: ");
        length = input.nextInt();
        System.out.print("Enter the Width: ");
        width = input.nextInt();

        for (int w = 0; w < length; w++) {
            for (int l = 0; l < width; l++) {
                System.out.print(" *");
            }
            System.out.println("");
        }
    }
}
}
于 2013-03-10T02:04:30.693 回答
0

将您的 int 数组更改为字符串数组

String[][] myarray = new String[width][length]; 

for (int w = 0; w < length; w++) {
    for (int l = 0; l < width; l++) {
        myarray[l][w]="*";
        System.out.print(" " + myarray[l][w]);
    }
    System.out.println("");
}
于 2014-10-14T14:33:30.893 回答