我正在尝试在我的游戏中制作一个for循环,以便当猜测的数量加起来时,它进入for循环并给出正确猜测的数量。这是我的计算机科学课,我们必须将for循环纳入程序。
if (guess1 == Secret_code[0]) {
System.out.println(" You have guessed one correctly in the right spot!");
}
if (guess2 == Secret_code[1]) {
System.out.println(" You have guessed one correctly in the right spot!");
}
if (guess3 == Secret_code[2]) {
System.out.println(" You have guessed one correctly in the right spot!");
}
if (guess4 == Secret_code[3]) {
System.out.println(" You have guessed one correctly in the right spot!");
}
do {
System.out.println("What is the number one peg in my code???");
guess1 = Guess.nextInt();
System.out.println("What is the number two peg in my code???");
guess2 = Guess.nextInt();
System.out.println("What is the number three peg in my code???");
guess3 = Guess.nextInt();
System.out.println("What is the number four peg in my code???");
guess4 = Guess.nextInt();
if (guess1 == Secret_code[0]) {
System.out.println(" You have guessed one correctly in the right spot!");
}
if (guess2 == Secret_code[1]) {
System.out.println(" You have guessed one correctly in the right spot!");
}
if (guess3 == Secret_code[2]) {
System.out.println(" You have guessed one correctly in the right spot!");
}
if (guess4 == Secret_code[3]) {
System.out.println(" You have guessed one correctly in the right spot!");
}
}
while ((guess1 != Secret_code[0]) & (guess2 != Secret_code[1]) & (guess3 != Secret_code[2]) & (guess4 != Secret_code[3]));
public static void CorrectGuess(int[] Secret_code) {
//Variables
int Correctspot;
for (Secret_code[0] = 0; Secret_code[0] < 3; Secret_code[0]++)
Correctspot = +1;
}
答案 0 :(得分:1)
我会告诉你一个例子,因为他们说这不是我们的工作,但我感觉很糟糕,因为他们是一些坏教师。我也会构建一个数组,因为这将解决你可能遇到的所有问题
//make a Scanner obj
Int[] guessArray = {10, 20, 30, 5};
int useranswer = 0;
int loopCount = 0;
while(loopCount < 4) {
System.out.println("blalalala for Guess #" + (loopCount+1));
useranswer = input.nextInt();
if(useranswer == guessArray[loopCount]) {
loopCount++;
}//end of if
}//end of while loop
拥有数组列表将有助于保持所有顺序,并且您可以在此循环之后在程序中重新设置值。您始终需要小心while
循环,因为如果代码错误,您最终可能会崩溃计算机。
我还会查找for
个循环,因为根据您未来的问题,for
或while
可以发挥最佳效果。
编辑后的编码风格[1]:注意:我通过将所有内容分开来编码,因为它可以帮助我查看所有内容,如果这是一个问题请告诉我。所以我可以在之后改变它