我正在为我的编程类制作这个老虎机但是我不知道如何让程序询问他们是否想要再次播放并因此再次运行而不会导致无限循环。任何帮助将不胜感激。
public static void main(String[] args)
{
boolean playAgain = true;
Scanner input = new Scanner(System.in);
System.out.println("Welcome, you have 10 credits! Play (Y/N)");
String choice;
choice = input.nextLine();
int credits = 10;
if ("y".equals(choice))
{
playAgain = true;
} else {
playAgain = false;
}
while (playAgain = true)
{
int sp0 = spin();
int sp1 = spin();
int sp2 = spin();
System.out.println(sp0 +"\t"+ sp1 +"\t"+ sp2);
int answer = evaluate(sp0,sp1,sp2);
int newCred = answer + credits - 1;
System.out.println("Your now have "+ newCred + " credits");
System.out.println("Press y to play again");
String newC = input.nextLine();
}
// TODO code application logic here
}
public static int spin()
{
int num1;
Random rand = new Random();
num1 = rand.nextInt(8);
return num1;
}
public static int evaluate(int e1, int e2, int e3)
{
int num;
if(e1==0 && e2==0 && e3==0)
{
num= 7;
System.out.println("You Win");
}else if (e1==e2 && e2 == e3){
num = 5;
System.out.println("You Win");
}else if ( e1== 0 && e2==0 && e3 != 0 ){
num= 3;
System.out.println("You win");
} else if (e1==e2 && e2==e1 && e3 != e1){
num= 2;
System.out.println("You win");
} else if (e1==0 && e2 !=0 && e3 != 0){
num= 1;
System.out.println("You win");
} else {
num =0;
System.out.println("You Lose");
}
return num;
}
答案 0 :(得分:2)
这一行可能不符合您的预期:
while (playAgain = true)
=
运算符用于分配,==
用于比较。
因此,此行将playAgain
的值设置为true
,
并且表达式的值也是true
,
所以这是一个无限循环。
你打算写的是:
while (playAgain == true)
但你根本不需要==
运算符,因为你可以直接使用布尔表达式,如下所示:
while (playAgain)
但这还不够。
在while
循环体内,您无需更改playAgain
的值。
解决这个问题的一种方法是:
while (playAgain) {
int sp0 = spin();
int sp1 = spin();
int sp2 = spin();
System.out.println(sp0 +"\t"+ sp1 +"\t"+ sp2);
int answer = evaluate(sp0,sp1,sp2);
int newCred = answer + credits - 1;
System.out.println("Your now have "+ newCred + " credits");
System.out.println("Press y to play again");
playAgain = "y".equals(input.nextLine());
}
答案 1 :(得分:0)
playAgain = true
将true赋予playAgain
playAgain == true
测试playAgain等于true