我不断收到错误,if
没有else
。
我试过else if
还有
for (;;){
System.out.println("---> Your choice: ");
choice = input.nextInt();
if (choice==1)
playGame();
if (choice==2)
loadGame();
if (choice==3)
options();
if (choice==4)
credits();
if (choice==5)
System.out.println("End of Game\n Thank you for playing with us!");
break;
else
System.out.println("Not a valid choice!\n Please try again...\n");=[;'mm
}
另外,如果您对如何呈现此代码有更好的想法,请不要犹豫:)
答案
因为你的else
不依附于任何东西。if
不带大括号仅包含紧随其后的单个语句。
if (choice==5)
{
System.out.println("End of Game\n Thank you for playing with us!");
break;
}
else
{
System.out.println("Not a valid choice!\n Please try again...\n");
}
不使用大括号通常被视为不好的做法,因为它可能会导致您遇到的确切问题。
此外,使用switch
这里会更有意义。
int choice;
boolean keepGoing = true;
while(keepGoing)
{
System.out.println("---> Your choice: ");
choice = input.nextInt();
switch(choice)
{
case 1:
playGame();
break;
case 2:
loadGame();
break;
// your other cases
// ...
case 5:
System.out.println("End of Game\n Thank you for playing with us!");
keepGoing = false;
break;
default:
System.out.println("Not a valid choice!\n Please try again...\n");
}
}
请注意,而不是无限for
循环我用了一个while(boolean)
,可以轻松退出循环。