我觉得这有点奇怪。我的循环不循环,我不知道为什么。没有错误消息。该程序只运行一次。这是我正在制作的游戏,它会让你掷出1-9个骰子,你可以选择从数字1-9列表中删除该数字,或者删除数字本身。这是支持发生,直到董事会中没有剩余数字。但是......循环不循环!!!
public class gudmundur_skilaverkefni9 {
public static void main (String[] args) {
System.out.println("Godan dag. Thu ert ad spila Larus.");
System.out.println("1 2 3 4 5 6 7 8 9");
int N = 9;
boolean[] Spilafylki = new boolean[10];
for (int i = 1; i <= N; i++) {
System.out.println("Sladu inn slembitolu til ad kasta teningunum.");
int teningakast = StdIn.readInt();
int teningatala = (int) (Math.random() * 10);
System.out.println("Thu fekkst " + teningatala + ".");
if (teningatala != 2) {
System.out.println("Viltu taka ut " + teningatala
+ " eda velja tvaer tolur sem mynda summu af "
+ teningatala + "? (1/2)");
int tala2 = StdIn.readInt();
if (tala2 == 2) {
System.out.println("Slaid inn fyrri tolu:");
int fyrritala = StdIn.readInt();
System.out.println("Slaid inn seinni tolu:");
int seinnitala = StdIn.readInt();
while (fyrritala+seinnitala != teningatala
|| fyrritala == seinnitala){
System.out.println("Thetta gengur ekki! Valdirdu nokkud somu toluna tvisvar? Reyndu aftur:");
System.out.println("Slaid inn fyrri tolu:");
fyrritala = StdIn.readInt();
System.out.println("Slaid inn seinni tolu:");
seinnitala = StdIn.readInt();
}
System.out.println("Nu litur spilid svona ut:");
Spilafylki[fyrritala] = true;
Spilafylki[seinnitala] = true;
for (i = 1; i <= N; i++) {
if (Spilafylki[i] == false)
System.out.print(i + " ");
else
System.out.print(" ");
}
System.out.println();
}
if (tala2 == 1) {
Spilafylki[teningatala] = true;
System.out.println("Nu litur spilid svona ut:");
for (i = 1; i <= N; i++) {
if (Spilafylki[i] == false)
System.out.print(i + " ");
else
System.out.print(" ");
}
System.out.println();
}
}
else {
System.out.println("Thu fekkst tvo. Ekki er hægt ad velja tvaer olikar natturulegar tolur sem mynda 2.");
System.out.println("Nu litur spilid svona ut:");
Spilafylki[teningatala] = true;
for (i = 1; i <= N; i++) {
if (Spilafylki[i] == false)
System.out.print(i + " ");
else
System.out.print(" ");
}
System.out.println();
int count = 0;
for (i = 1; i <= N; i++)
if (Spilafylki[i] == true)
count++;
if (count == 9) {
System.out.println("Allar tolurnar eru farnar. Takk fyrir ad spila Larus.");
break;
}
}
}
}
答案 0 :(得分:1)
这很简单:在嵌套循环中,您不会重新声明 i 变量,因此使用外部循环相同的变量。这样,只要其中一个嵌套循环结束, i 将等于 N ,创建正确的条件,使第一个循环在第一个循环后立即完成周期。
所以,要么通过在嵌套循环中重新声明 i 变量来掩盖外部的 i
for (int i = 1; ...
在 i 前放置 int 会遮盖当前词法范围中的那个。 或者,为了更具可读性,请为每个循环使用不同的变量名称。