I am trying to create a simple java program for a chess tournament, which will save game results in an array. Results will be stored according to users choice, they may be input from keyboard, or using results that are already in the array, OR generate random sequence of numbers 1.0, 0.0, 0.5. (win, loss, draw)
So far I know how to generate random numbers in a specific range, using java.util.Random;
public static void main(String[] args) {
double a[][] = {{0.5, 0.5, 0.5, 0.5, 0.5},
{0, 1, 0, 1, 1},
{0.5, 1, 0.5, 0.5, 0},
{0, 0.5, 0, 0.5, 0},
{1, 1, 1, 1, 1},
{0, 0, 0, 0.5, 0.5},
{0, 0.5, 0, 0, 1}};
int i, j;
int ch;
System.out.print("mode (1, 2 or 3): ");
Scanner sc = new Scanner(System.in);
ch = sc.nextInt();
Random rnd = new Random();
switch (ch) {
case 1 -> { for (i=0; i<a.length ;i ) {
for (j=0; j<a[i].length; j ) {
a[i][j] = sc.nextDouble();
}
}
}
case 2 -> { for (i=0; i<a.length; i ) {
for (j=0; j<a[i].length; j ) {
a[i][j] = rnd.nextDouble();
}
}
}
case 3 -> { for (i=0; i<a.length; i ) {
for (j=0; j<a[i].length; j ) {
a[i][j] = a[i][j];
}
}
}
default -> {
System.out.println("mode error");
sc.close();
return;
}
}
sc.close();
for (i=0; i<a.length; i) {
for (j=0; j<a[i].length; j) {
System.out.printf("%.1f" " ", a[i][j]);
}
System.out.println();
}
so case 2 of switch statement is giving me issues, since it gives an output of random numbers in a range of 0 to 1, but game results must be stored in values of 1.0, 0.5, and 0.0
CodePudding user response:
Use nextInt(bound)
with a bound of 3, to generate 0, 1, 2
, then divide by 2
case 2 -> {
for (i = 0; i < a.length; i ) {
for (j = 0; j < a[i].length; j ) {
a[i][j] = rnd.nextInt(3) / 2.0;
}
}
}
Note that case 3
is useless, it does nothing, the following is enough
case 3 -> System.out.println("Nothing to do");
CodePudding user response:
You can make a new function in which you make your array for specific value then return a random value from that array and call that random function that you made in for loop like this:
import java.util.Random;
public static Double RandomGenerator() {
Double[] arr = new int[] { 0.0 , 0.5, 1.0 };
Double result = arr[new Random().nextDouble(arr.length)]);
return result
}
}
Then in your for loop you can do this:
{ for (i=0; i<a.length; i ) {
for (j=0; j<a[i].length; j ) {
a[i][j] = RandomGenerator();
}
Which will return a double random value in your array.
CodePudding user response:
You can have your possible valid values in an array:
float[] valuesArray = {1.0,0.0,0.5};
And then use something like the following to generate a valid index of the array that you can use to access one of your valid values:
public int getRandomNumber(int min, int max) {
return (int) ((Math.random() * (max - min)) min);
}
So if you call it like int myIndex = getRandomNumber(0, 2);
and use its return value to access values from valuesArray
you should be able to get only 0.0, 0.5 and 1.0.