backEnd类中的for循环 - CompareGuess方法不起作用。 .................................................. .................................................. ................................................
public class frontEnd
{
public static void main (String args[])
{
int GetGuess = 0;
backEnd e1 = new backEnd();
e1.InitializeArray();
while(e1.chanceCounter<3)
{
System.out.println("Enter a number");
GetGuess = (int)(Math.random()*6);
System.out.println(GetGuess);
e1.UserGuess(GetGuess);
e1.CompareGuess();
if(e1.suc!=1)
{
System.out.println("It is a miss");
}
}
System.out.println("Sorry, no chances left");
}
}
class backEnd
{
int Guess;
int HitCounter=0;
int[] abc = new int[7] ;
int chanceCounter=0;
int suc = 0;
int x =0;
public void InitializeArray()
{
abc[1]= 3;
abc[2] = 5;
abc[4] = 1;
}
public void UserGuess(int guess)
{
Guess = guess;
}
public void CompareGuess()
{
for(x=0; x<=6; x++ )
{
if (abc[x] == Guess)
{
System.out.println("It is a hit");
chanceCounter = chanceCounter + 1;
suc = 1;
}
break;
}
}
}
答案 0 :(得分:0)
问题似乎在这里:
for(x=0; x<=6; x++ )
{
if (abc[x] == Guess)
{
System.out.println("It is a hit");
chanceCounter = chanceCounter + 1;
suc = 1;
}
break; //Here
}
查看代码的作用:
for
循环进行第一次迭代,x = 0
如果abc[x]
等于Guess
,则程序会执行if语句中的代码。之后,将执行break语句。
如果没有,则只执行break
声明
因此,在这两种情况下,break
语句将在第一次迭代中执行(因此,您的程序将退出for
循环)。
看看你的程序只会执行你的第一次迭代而不是其余的(x = 1, x = 2 [....] x =6)
。
如果您希望for
循环完成所有迭代,则必须从代码中删除break
语句。
我希望它会对你有所帮助!
答案 1 :(得分:0)
因为你的游戏就是猜测。我猜测了它应该做什么,然后我重写了你的代码,因为我无法忍受将它保留原样。我把它留给了我可以应付的相似之处:
public class FrontEnd
{
public static void main (String args[])
{
int getGuess = 0;
BackEnd e1 = new BackEnd();
e1.initializeArray();
int totalChances = 3;
while(e1.chanceCounter < totalChances)
{
System.out.println("Enter a number");
getGuess = (int)(Math.random()*6);
System.out.println(getGuess);
e1.userGuess(getGuess);
e1.compareGuess();
if(!e1.suc)
{
System.out.println("It is a miss");
}
e1.suc = false;
e1.chanceCounter++;
}
System.out.println("Sorry, no chances left");
System.out.println("you scored " + e1.hitCounter + " out of " + totalChances);
}
}
class BackEnd
{
int guess;
int hitCounter = 0;
int[] abc = new int[7] ;
int chanceCounter = 0;
boolean suc = false;
public void initializeArray()
{
abc[1] = 3;
abc[2] = 5;
abc[4] = 1;
}
public void userGuess(int guess)
{
this.guess = guess;
}
public void compareGuess()
{
for( int x = 0; x <= 6; x++ )
{
if (abc[x] == guess)
{
System.out.println("It is a hit");
hitCounter++;
suc = true;
break;
}
}
}
}
正如其他人所说,break
语句应该在条件块内。此外,您似乎忘记在每次猜测后重置suc
变量。你也根本没有使用hitCounter
。我假设计算正确的猜测,这让我想知道何时更新chanceCounter
:在每次猜测之后或在每次错误猜测之后。在3次猜测之后,或者经过3次错误的猜测之后,我都不知道猜测者是否会失去机会。我选择了前者并在每次猜测后更新chanceCounter
。
0的猜测被认为是正确的,因为它们与abc
数组中未初始化的所有条目匹配。