我在这个程序中遇到了我的while循环问题,显然我希望循环在玩家获胜时退出,但重新开始直到他们在我的菜单上选择“退出”。习惯使用C ++并且能够使用布尔值true或false退出循环,出于某些原因无效或者我无法在java中弄清楚。相反,每当玩家获胜或失败时我都使用变量cont,并使用循环的continue语句重新评估。在我的while循环中嵌套的switch语句中继续是合法的吗?让这个工作的最佳方法是什么?在我的交换机的情况2中,我的IDE也为我的break语句提供了“无法访问”的错误。
我正在寻找一个更简单的解决方案吗?
import java.io.*;
import java.util.Scanner;
public class BlackJack
{
static void printCard(int x){
if (x == 13)
{
System.out.println("Your card is a KING!");
}
else if (x == 1)
{
System.out.println("Your card is an ACE!");
}
else if (x == 11)
{
System.out.println("Your card is a JACK!");
}
else if (x == 12)
{
System.out.println("Your card is a QUEEN!");
}
else
{
System.out.print("Your card is a " + x);
System.out.println("!");
}
}
public static void main(String[] args)
{
int wincount = 0;
int tiecount = 0;
int losecount = 0;
int gamecount = 1;
int cont =1;
double winpercent = 0.0;
Scanner input = new Scanner(System.in);
P1Random rng = new P1Random();
int card = 0;
int totalhandp = 0;
int totalhandd = 0;
System.out.println("START GAME #" + gamecount);
card = rng.nextInt(13) + 1;
totalhandp = card;
printCard(card);
while (cont < 2)
{
Scanner opt = new Scanner(System.in);
System.out.println(" 1. Get another card \n 2. Hold hand \n 3. Print statistics \n 4. Exit");
int menuopt = opt.nextInt();
switch (menuopt)
{
case 1:
card = rng.nextInt(13) + 1;
totalhandp = totalhandp + card;
printCard(card);
if (totalhandp == 21)
{
System.out.println("BLACKJACK! You win!");
wincount++;
gamecount++;
cont++;
continue;
}
break;
case 2:
totalhandd = rng.nextInt(26) + 17;
if (totalhandd > 21)
{
System.out.println("You win!");
wincount++;
gamecount++;
cont++;
continue;
}
if (totalhandd == totalhandp)
{
System.out.println("It's a tie! No one wins!");
tiecount++;
gamecount++;
cont++;
continue;
}
else
{
int diff1 = 0;
int diff2 = 0;
diff1 = 21 - totalhandp;
diff1 = 21 - totalhandp;
if (diff1 < diff2)
{
System.out.println("You win!");
wincount++;
gamecount++;
cont++;
continue;
} else
{
System.out.println("You lose!");
losecount++;
gamecount++;
cont++;
continue;
}
}
break;
case 3:
winpercent = (wincount / gamecount);
System.out.println("Games played: " + gamecount);
System.out.println(" Games won: " + wincount);
System.out.println(" Games tied: " + tiecount);
System.out.println(" Games lost: " + losecount);
System.out.println(" Win percentage: " + winpercent);
break;
case 4:
System.exit(0);
break;
default:
System.out.print("Invalid input! \n Please enter a value between 1 and 4 ");
break;
}
}
System.out.println("You exceeded 21! You lose.");
losecount++;
gamecount++;
cont = 2;
}
}
发布于 2018-09-19 13:52:49
从代码中删除了一些内容,用一个简单、简短和独立的代码段将问题隔离开来:
class Foo {
public static void main(String[] args) {
while(true) {
switch(0) {
case 0:
if (true) {
continue;
} else {
continue;
}
break;
}
}
}
}
Foo.java:11: error: unreachable statement
break;
^
1 error
https://stackoverflow.com/questions/-100002695
复制相似问题