我要做的是创建一个程序,该程序将随机选择一个1到100之间的整数。然后,请用户猜测一下。循环直到他们这样做,并且在每次错误的猜测之后告诉他们它们太高还是太低。我想使用两种不同的方法来验证其输入。一个用于测试它是否为有效的int,另一个用于测试范围(1-100)。此秒将需要另一个参数作为高范围值。
我遇到的问题:
while (guess != a) {
之前必须多次输入数字。控制台示例:
I am thinking of a number from 1 to 100 ... guess what it is ?6
I am thinking of a number from 1 to 100 ... guess what it is ?6
I am thinking of a number from 1 to 100 ... guess what it is ?6
6
higher!
再次从控制台示例:
`I am thinking of a number from 1 to 100 ... guess what it is? 10001
I am thinking of a number from 1 to 100 ... guess what it is? 10001
Error! Must be less than 100
I am thinking of a number from 1 to 100 ... guess what it is? 10001
100
lower!
10001
lower!`
package labbs;
import java.util.Scanner;
public class Lab12 {
public static double getDoubleGreaterThan(double low, Scanner input, String prompt) {
double num;
num = getDouble(input,prompt);
if(num <= low)
System.out.println("Error! Must be greater than 1");
num = getDouble(input,prompt);
if (num > 100)
System.out.println("Error! Must be less than 100");
num = getDouble(input,prompt);
return num;
}
public static double getDouble(Scanner input, String prompt) {
boolean OK;
double val=0;
do {
System.out.print(prompt);
OK = true;
try {
val = input.nextDouble();
}
catch(Exception e) {
OK = false;
System.out.println("Error! Invalid input. Must be a double value");
input.next();
}
}while(! OK);
return val;
}
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
double output, letscheck;
int count=0, guess=0;
int a=1 + (int) (Math.random() * 99);
letscheck = getDoubleGreaterThan(-0.9, keyboard,"I am thinking of a number from 1 to 100"
+ " ... guess what it is ?");
while (guess != a) {
guess = keyboard.nextInt();
count++;
if (guess > a) {
System.out.println("lower!");
} else if (guess < a) {
System.out.println("higher!");
}
}
System.out.println("Congratulations. You guessed the number with "
+ count + " tries!");
}
}
答案 0 :(得分:0)
1。查询:您刚刚错过了getDoubleGreaterThan()
方法中的括号,因为如果语句块始终无法在输入的基础上正常工作,请按如下所示更改代码:
public static double getDoubleGreaterThan(double low, Scanner input, String prompt) {
double num;
num = getDouble(input,prompt);
if(num <= low){
System.out.println("Error! Must be greater than 1");
num = getDouble(input,prompt);
}
if (num > 100){
System.out.println("Error! Must be less than 100");
num = getDouble(input,prompt);
}
return num;
}