我是一名寻求帮助的新手编码员。我必须编写这个程序,用户猜到0到100之间的数字,然后在响应中被告知它是高还是低。下面是代码。我的问题是,有时当我输入一个数字时,通常99程序终止,我不知道为什么。我一直在查看代码2个小时,无法弄清楚导致程序终止的原因。任何帮助将不胜感激。
import java.util.Scanner;
import java.util.Random;
public class Proj71 {
private static int userNumber;
private static int firstguess = 1;
private static int numguess1;
private static int numguess2;
private static int totalguess;
private static Random generator = new Random();
private static Scanner reader = new Scanner(System.in);
private static int compNumber = generator.nextInt(100);
public static void main(String[] args) {
UserGuess();
UserHighGuess();
UserLowGuess();
UserEquals();
}
private static void UserGuess() {
System.out.println("What number am I thinking of between 0 and 100?: ");
userNumber = reader.nextInt();
}
private static void UserHighGuess() {
while (userNumber > compNumber) {
System.out.println("Lower! Try again: ");
userNumber = reader.nextInt();
numguess1++;
}
}
private static void UserLowGuess() {
while (userNumber < compNumber) {
System.out.println("Higher! Try again: ");
userNumber = reader.nextInt();
numguess2++;
}
}
private static void UserEquals() {
if (userNumber == compNumber) {
totalguess = numguess1 + numguess2 + firstguess;
System.out.println("You got it!");
System.out.println("Total number of guess: " + totalguess);
}
}
}
谢谢, Jmanlikescake(对不起,如果这篇文章真的很糟糕)
答案 0 :(得分:2)
问题在于程序的结构。
您正在致电
UserGuess();
UserHighGuess();
UserLowGuess();
UserEquals();
如果数字为50,用户猜到了30,该怎么办?我们将在UserLowGuess()的主体中。 然后想象用户输入55. UserLowGuess()将被打破,因为userNumber大于compNumber。那么,你将在UserEquals中。但由于55不等于50,因此不会输入if语句,程序将退出。
答案 1 :(得分:0)
我建议把它放在一个while循环中,而不是三个。我没有对此进行测试,仅供参考。
这会循环继续接受用户输入,直到找到匹配为止。
public static void main(String[] args) {
UserGuess();
}
private static void UserGuess() {
System.out.println("What number am I thinking of between 0 and 100?: ");
userNumber = reader.nextInt();
totalguess = 1;
while (userNumber != compNumber) {
if (userNumber > compNumber) {
System.out.println("Lower! Try again: ");
} else if (userNumber < compNumber) {
System.out.println("Higher! Try again: ");
}
userNumber = reader.nextInt();
totalguess++;
}
System.out.println("You got it!");
System.out.println("Total number of guess: " + totalguess);
}