1
votes

Créez un tableau 10x2 bidimensionnel, chaque élément étant défini sur la chaîne "x"

Comme le titre l'indique, je souhaite créer un tableau qui génère ce qui suit mais je n'ai pas d'idée sur la façon de procéder:

public static void designs() {
    String[][] canvas = new String[10][10];
    for (int i = 0; i < canvas.length; i++) {
        for (int j = 0; j < canvas[0].length; j++) {
            if (i == j) {
                canvas[j][i] = "x";
            } else {
                canvas[j][i] = "x";
            }
        }
    }
    for (int a = 0; a < canvas.length; a++) {
        for (int b = 0; b < canvas[0].length; b++) {
            System.out.print(canvas[a][b] + "\t");
        }
        System.out.println("\n");
    }
}

Et voici le code sur lequel j'ai commencé à travailler pour faire ceci:

x x
x x
x x
x x
x x
x x
x x
x x
x x
x x


0 commentaires

3 Réponses :


4
votes

Vous créez un tableau 10x10 au lieu d'un 10x2 ( new String [10] [2] ) et effectuez une manipulation étrange lorsque canvas [i] [j] = "x" ; serait suffisant, ici:

canvas[j][i] = "x";

Ce qui est en fait équivalent à

if (i == j) {
    canvas[j][i] = "x";
} else {
    canvas[j][i] = "x";
}

On dirait que vous venez de confondre les index.


0 commentaires

1
votes

Si vous souhaitez créer une matrice contenant des caractères, vous devez créer la matrice de type de données de caractères afin que la taille puisse être optimisée.

import java.io.*;

public class Main {
    public static void main(String[] args)
            throws NumberFormatException, IOException {

        // For taking input from user : console input
        InputStreamReader r = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(r);

        System.out.println("Enter the size of rows : ");
        int rows = Integer.parseInt(br.readLine());
        System.out.println("Enter the size of columns : ");
        int cols = Integer.parseInt(br.readLine());

        Character[][] canvas = new Character[rows][cols];

        for (int i = 0; i < canvas.length; i++) {
            for (int j = 0; j < canvas[0].length; j++) {
                canvas[i][j] = 'x';
            }
        }

        //for each loop
        for (Character[] lines : canvas) {
            for (Character car : lines) {
                System.out.print(car + " ");
            }
            System.out.println();
        }
    }
}


0 commentaires

0
votes

Créer un tableau 2D 10x2 et le remplir de symboles X :

X X
X X
X X
X X
X X
X X
X X
X X
X X
X X
// output
Arrays.stream(arr).map(row -> String.join(" ", row)).forEach(System.out::println);
int m = 10;
int n = 2;
String[][] arr = IntStream.range(0, m)
        .mapToObj(i -> IntStream.range(0, n)
                // a string with the symbol X
                .mapToObj(j -> "X")
                .toArray(String[]::new))
        .toArray(String[][]::new);


0 commentaires