I am a novice to java. Im trying to write a two-dementional array that writes out a lottery ticket (6 integers) 10 times
int[][] lottery = new int[6][10];
for (int i=0; i < lottery.length; i++)
for (int j=0; j < lottery[0].length; j++)
lottery[i][j] = (int)(50.0 * Math.random());
for (int i=0; i < lottery.length; i++)
for (int j=0; j < lottery[0].length; j++)
{
/*if i < lottery.length
System.out.print(lottery[i][j] + " ");
else
System.out.println(lottery[i][j]);*/
}
How do I write it out as 10 rows of 6 integers
23 12 31 49 3 17
9 1 22 13 36 50
.
.
.
Your array is backwards. If you want to be able to output 10 rows of 6 numbers with the nested for loops that you have, you would need the array to be int lottery[][] = new int[10][6];
Then to output it, you'd simply need to do:
for (int i=0; i < lottery.length; i++){
for (int j=0; j < lottery[i].length; j++){
System.out.print(lottery[i][j]+"");
if(j < lottery[i].length -1){
System.out.print(" ");
}
}
System.out.print("\n");
}
The call to System.out.print will print the text without a new-line character so you can keep appending to the same line.
Java (like C), stores multidimensional arrays in Row-major order . Depending on your mindset this may seem natural or not but just remember arrays are referenced by [row][col]
, not [col][row]
.
Your array int[][] lottery = new int[6][10];
is 6 rows, 10 cols each. Based on your description, I think you want 10 rows or 6 cols each or int[][] lottery = new int[10][6];
Then print it:
for (int i=0; i < lottery.length; i++)
{
for (int j=0; j < lottery[0].length; j++)
{
if (j < (lottery[0].length+1)
{
System.out.print(lottery[i][j] + " ");
}
else
{
System.out.println(lottery[i][j]);
}
}
}
10 rows of 6 integers:
int[][] lottery = new int[10][6];
Formatted printing:
for(int row=0; row<nums.length; row++) {
for(int col=0; col<nums[row].length; col++) {
System.out.printf("%2d", nums[row][col]);
}
System.out.print("\n");
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.