我尝试创建基本号码查找游戏(1-100)。 但总是在第二次尝试后程序终止。
代码:
Random rnd = new Random();
int rndm = rnd.nextInt(100);
int tryn;
Scanner sc = new Scanner(System.in);
System.out.print("Guess: ");
tryn = sc.nextInt();
if (tryn == rndm) {
System.out.println("You win.");
sc.close();
}
else if (tryn > rndm) {
System.out.println("Too high.");
System.out.print("Guess again: ");
tryn = sc.nextInt();
}
else {
System.out.println("Too low.");
System.out.print("Guess again: ");
tryn = sc.nextInt();
}
当我运行输出时:
<terminated> test2 [Java Application]...
Guess: 30
Too low.
Guess again: 50
为什么我的程序没有循环?谢谢你的帮助。
答案 0 :(得分:2)
在代码中添加循环...
while(tryn != rndm){
答案 1 :(得分:1)
请参阅以下代码(我已测试过):
import java.util.Random;
import java.util.Scanner;
public class Guess {
public static void main(String[] args) {
Random rnd = new Random();
int rndm = rnd.nextInt(100);
int tryn;
Scanner sc = new Scanner(System.in);
System.out.print("Guess: ");
while (sc.hasNextInt()) {
tryn = sc.nextInt();
if (tryn == rndm) {
System.out.println("You win.");
break;
} else if (tryn > rndm) {
System.out.println("Too high.");
System.out.print("Guess again: ");
} else {
System.out.println("Too low.");
System.out.print("Guess again: ");
}
}
sc.close();
}
}