Good evening, I have to fill in a grid that I created by adding 4 random letters in it. I don't know how to get started, I have an array [i=5][j=4] and I have to add to a random i and j a G and that 4 times. I am aware of having to use Math.random() as well as a while(x<4) but I don't know how to go about it.enter image description here
package tp1;
import java.util.*;
import java.lang.Math;
public class Joueur {
//attributs
String pseudo;
private char[][] grille;
private int nbreManches;
private int nbreObstacles;
//constructeurs
public Joueur(String valeur) {
nbreManches = 0;
nbreObstacles = 0;
grille = new char[5][4];
pseudo = valeur;
}
public Joueur() {
Scanner sc = new Scanner(System.in);
System.out.println("Quel est votre pseudo ?");
pseudo = sc.nextLine();
nbreManches = 0;
nbreObstacles = 0;
grille = new char[5][4];
}
public void afficher() {
grille = new char[5][4];
System.out.println("************************************");
System.out.println("Pseudo: " + pseudo);
System.out.println("Nombre de manches: " + nbreManches);
System.out.println("Nombres d'obstacles: " + nbreObstacles);
System.out.println();
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
System.out.print("|");
}
System.out.println("|");
}
System.out.println();
}
}
I don't know from your description where in the grid you want the letters to be, but I can give this hints:
Math.random()
is always in the range 0 <= x < 1. If you want a number 0 <= x <= y you multiply Math.random()
with y + 1 and convert it to int
. (conversion to int
truncates the number, so for example truncate(0.999 * 25) will always be < 24, hence +1)char
is also a number, you can apply numeric operations on it.Knowing this and that the alphabet has 26 characters you can write:
private static char randomLetter() {
int i = (int) (Math.random() * 26); // 0 ... 25
int j = (int) (Math.random() * 2); // upper case yes/no
if (j == 1) {
return (char) ('A' + i);
}
return (char) ('a' + i);
}
Is that what you're looking for?