我的程序能够正常工作,但不会打印时它应该是
问题描述:
我是新来的java编程,并正在测试一些我学到的东西,以便做出一个小猜谜游戏。它可以工作,你可以通过它,但是当你得到第二个错误的数字后,你不会被告知你这个数字是低还是高。这是问题的一个例子:我的程序能够正常工作,但不会打印时它应该是
Guess a number, 1 through 100:
50
Guess higher!
75
75
Guess lower!
65
65
Guess lower!
这里是代码:如果块
public static void main(String[] args) {
Random num = new Random();
Scanner scan = new Scanner(System.in);
int rand;
boolean test;
int rand2;
int guess = 0;
rand = num.nextInt(100);
System.out.println("Guess a number, 1 through 100: ");
while(test = true){
rand2 = scan.nextInt();
if(rand == rand2){
guess++;
if(guess < 19){
System.out.println("Thats the correct number! And it only took: " + guess + " tries");
}else{
System.out.println("It took you: " + guess + " tries to guess the number!");
}
}else if(rand < rand2){
System.out.println("Guess lower! ");
guess++;
rand2 = scan.nextInt();
}else if(rand > rand2){
System.out.println("Guess higher! ");
guess++;
rand2 = scan.nextInt();
}
}
}
答
在别的都删除rand2 = scan.nextInt();
并尝试运行它。你的逻辑就像用户输入两次,直到你得到正确的答案。
答
在进行下一个更低或更高检查之前,您正在扫描另一个数字两次。一旦进入if语句,另一个进入while循环的顶部。尝试删除if/else语句中的scan.nextInt()静态方法调用,它应该像你想要的那样工作。
while(test = true){
rand2 = scan.nextInt();
guess++;
if(rand == rand2){
if(guess < 19){
System.out.println("Thats the correct number! And it only took: " + guess + " tries");
break;
}else{
System.out.println("It took you: " + guess + " tries to guess the number!");
}
}else if(rand < rand2){
System.out.println("Guess lower! ");
}else if(rand > rand2){
System.out.println("Guess higher! ");
}
}
答
我有正确的为你,看到如下:
public static void main(String[] args) {
Random num = new Random();
Scanner scan = new Scanner(System.in);
boolean isOK = false;
int counter = 0;
int randNum = num.nextInt(100);
while(true) {
counter++;
int n = scan.nextInt();
if(n == randNum) {
System.out.println("OK in " + counter + " times");
isOK = true;
} else if(n > randNum) {
System.out.println("Lower");
} else {
System.out.println("Higher");
}
}
}
我看到的第一个问题,你看在这两个条件下一个int和再次在环(所以第一个的开始猜测下/更高后忽略)。 – AxelH
[什么是调试器,它如何帮助我诊断问题?]可能的重复(http://*.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-我诊断的 - 问题) – Raedwald