[英]Java - Assign the correct number from list
I have a non-repeated Shuffled list between 1 and 16 and a 2D array, What I'm trying to do is assing the number 16 to the position btn[3][3], all the other positions can have the other remaining list values (1 - 15)我有一个 1 到 16 之间的非重复随机列表和一个二维数组,我想要做的是将数字 16 分配给位置 btn[3][3],所有其他位置都可以有其他剩余的列表值 (1 - 15)
Code:代码:
int c = 0;
int v = 0;
for (int i=0; i<4; i++) {
v=0;
for(int j=0; j<4; j++){
String number = Integer.toString(list.get(c));
c++;
if (i == 3 && j == 3){
JButton btnmix = new JButton();
btnBotonMix[i][j] = btnmix;
btnBotonMix[i][j].setBounds(70+90*(i%10),v+90*(i/10),90,90);
btnBotonMix[i][j].setText(number);
}
else{
JButton btnmix = new JButton();
btnBotonMix[i][j] = btnmix;
btnBotonMix[i][j].setBounds(70+90*(i%10),v+90*(i/10),90,90);
btnBotonMix[i][j].setText(number);
}
v = v + 90;
}
}
What I'm looking for, is to always assign the number 16 in my index btn[3][3]我正在寻找的是始终在我的索引 btn[3][3] 中分配数字 16
So I want get this (the number 16 always in [3][3] and all the remaining ones in a random position):所以我想得到这个(数字 16 总是在 [3][3] 中,所有剩余的都在随机位置):
[0][0] 15
[0][1] 11
[0][2] 14
[0][3] 5
[1][0] 12
[1][1] 3
[1][2] 8
[1][3] 9
[2][0] 6
[2][1] 2
[2][2] 13
[2][3] 1
[3][0] 4
[3][1] 7
[3][2] 10
[3][3] 16
// always put 16 last
final int lastNumber = 16;
// take it out from the list from the start
list.remove(Integer.valueOf(lastNumber));
for (int i = 0; i < 4; i++) {
v = 0;
for (int j = 0; j < 4; j++) {
String number;
if (i == 3 && j == 3) {
number = Integer.toString(lastNumber);
} else {
number = Integer.toString(list.get(c));
c++;
}
JButton btnmix = new JButton();
btnBotonMix[i][j] = btnmix;
btnBotonMix[i][j].setBounds(70 + 90 * (i % 10), v + 90 * (i / 10), 90, 90);
btnBotonMix[i][j].setText(number);
v = v + 90;
}
}
Please try this and let me know -请试试这个,让我知道 -
int c = 0;
int v = 0;
Arrays.sort(list);//added
for (int i = 0; i < 4; i++) {
v = 0;
for (int j = 0; j < 4; j++) {
String number = Integer.toString(list.get(c)); //Changed
c++;
if (i == 3 && j == 3) {
JButton btnmix = new JButton();
btnBotonMix[i][j] = btnmix;
btnBotonMix[i][j].setBounds(70+90*(i%10),v+90*(i/10),90,90);
btnBotonMix[i][j].setText(number);
} else {
JButton btnmix = new JButton();
btnBotonMix[i][j] = btnmix;
btnBotonMix[i][j].setBounds(70+90*(i%10),v+90*(i/10),90,90);
btnBotonMix[i][j].setText(number);
}
v = v + 90;
}
}
I do not think now you would need if else here.我不认为现在你会需要在这里。
The most simplest way is to check if the number retrieved is 16 when you reach the position [3][3]最简单的方法是在到达位置[3][3]时检查检索到的数字是否为16
int c = 0;
for (int i=0; i<a.length; i++) {
for(int j=0; j<a.length; j++){
String number = list.get(c);
c++;
JButton btnmix = new JButton();
btnBotonMix[i][j] = btnmix;
btnBotonMix[i][j].setBounds(70+90*(i%10),v+90*(i/10),90,90);
if (i == 3 && j == 3){
if(number.equals("16")){
btnBotonMix[i][j].setText(number);
}
}
else{
btnBotonMix[i][j].setText(number);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.