我的代码运行正常,但我使用扫描仪的每一行都警告我有“资源泄漏;'userGuess'永远不会关闭”我不明白这意味着什么,可以使用一些帮助来解决它。此外,如果我的代码中有任何其他内容值得修复,我可以使用帮助。请注意,我对Java编程知之甚少。我也无法让我的TryCounter ++工作......
package masterMind2_1;
import java.util.Scanner;
public class MasterMind2_1 {
public static void main(String[] args) {
System.out.println("This is MasterMind, a logic game");
System.out.println("To win you must guess correctly where each number is(The Numbers Range from 1-4)");
System.out.println("You will be told if you get one correct");
System.out.println("You will only get 10 tries, then you lose");
System.out.println("Lets begin");
//Declare Array
int [] answerArray;
answerArray= new int [4];
//Initialize Array
//Change these value to change the answers needed to win
answerArray[0]=2;
answerArray[1]=3;
answerArray[2]=2;
answerArray[3]=2;
// //Create Board
// System.out.println("-- -- -- --");
boolean guessedAll = false;
int guessedCount=0;
int tryCounter=0;
while(tryCounter<9 || !guessedAll){
System.out.println("What is the first Number?");
Scanner userGuess = new Scanner(System.in);
int num = userGuess.nextInt();
if (num==answerArray[0]) {
guessedCount++;
}
System.out.println("What is the Second Number?");
Scanner userGuess1 = new Scanner(System.in);
int num1 = userGuess1.nextInt();
if (num1==answerArray[1]) {
guessedCount++;
}
System.out.println("What is the Third Number?");
Scanner userGuess2 = new Scanner(System.in);
int num2 = userGuess2.nextInt();
if (num2==answerArray[2]) {
guessedCount++;
}
System.out.println("What is the Fourth Number?");
Scanner userGuess3 = new Scanner(System.in);
int num3 = userGuess3.nextInt();
if (num3==answerArray[3]) {
guessedCount++;
}
System.out.println("Your guess was "+ num+" "+num1+" "+num2+" "+num3);
if (num==answerArray[0]) {
System.out.println("First number was correct");
} else {
System.out.println("First number was incorrect");
}
if (num1==answerArray[1]) {
System.out.println("Second number was correct");
} else {
System.out.println("Second number was incorrect");
}
if (num2==answerArray[2]) {
System.out.println("Third number was correct");
} else {
System.out.println("Third number was incorrect");
}
if (num3==answerArray[3]) {
System.out.println("Fourth number was correct");
} else {
System.out.println("Fourth number was incorrect");
}
if (guessedCount==4) {
System.out.println("YAY you won!!");
guessedAll=true;
tryCounter=10;
} else {
System.out.println("Try again, except this time don't fail!");
guessedAll=false;
tryCounter++;
guessedCount=0;
}
}//What if I collected all of the values first
} //then told them if they were right or Wrong?
//Black and White Pegs?
//Fix TryCounter...Why isn't it working
}
感谢您的帮助!
答案 0 :(得分:3)
错误消息告诉您,您永远不会在Scanner对象上调用close()
方法。更糟糕的问题是,只需要一个扫描仪即可创建多个扫描仪。
至于tryCounter
没有工作......
while(tryCounter<9 || !guessedAll)
如果条件的任何一部分为真,这将保持循环。我的猜测是!guessedAll
正在评估超过9个猜测的真值,所以你的循环继续运行。您需要将||
更改为&&
以使其在9次尝试后停止循环。 (另外,打印出变量的值或使用调试器,以便在预期时验证它们是否正在发生变化。)