我正在尝试移动2D数组中的元素(特别是方形矩阵),以便结果是一个"阶梯"图案:
原件:
1 2 3 4 5
10 6 7 8 9
14 15 11 12 13
18 19 20 16 17
22 23 24 25 21
目标:
public class StaircaseMatrix
{
public static void main(String[] args)
{
int[] num = {1,2,3,4,5};
shiftRight(num);
System.out.println("After shifting the array is:");
for (int x = 0; x < num.length; x++)
System.out.print(num[x] + " ");
}
public static void shiftRight(int[] list)
{
int last = list[list.length - 1];
for (int j = list.length - 1; j > 0; j--) {
list[j] = list[j - 1];
}
list[0] = last;
}
}
我设法编写了一个程序,可以在一维数组中为矩阵的第一行执行任务(见下面),但我似乎无法翻译代码,使其在2D数组中运行。
import java.util.*;
public class GameOfCraps {
public static void main(String[] args) {
Random rn = new Random();
int counterw = 0;
int counterl = 0;
int countsum = counterl + counterw;
int points = 0;
do {
int rndice1 = rn.nextInt(5) + 1; // 1 to 6
int rndice2 = rn.nextInt(5) + 1;// 1 to 6
int sum = rndice1 + rndice2;// sum of dice random
if (sum == 2 || sum == 3 || sum == 12) {
// System.out.println("you lose");
counterl++;
}
else if (sum == 7 || sum == 11) {
// System.out.println("you won");
counterw++;
}
else {
do {
boolean xc = false;
points = sum;
int rndice3 = rn.nextInt(5) + 1;
int rndice4 = rn.nextInt(5) + 1;
if (rndice3 + rndice4 == points) {
// System.out.println("you won");
counterw++;
xc = true;
//break;
}
if (xc == false)
counterl++;
} while (points != 7);
}
} while (countsum <= 10000);
System.out.println(counterw);
System.out.println(counterl);
System.out.println("probability of winning the game: "+(double)(counterw)/(counterw+counterl));
}
&#13;
答案 0 :(得分:0)
shiftRight()
为array2D[0]
0次,array2D[1]
为1次,array2D[2]
为2次,依此类推,使用for
循环。