我的程序应该执行以下步骤:
(h/l/c)
? (用户必须输入其中一个)。(y/n)
? (用户必须回答(y/n)
)我能够执行问题1。问题2,随机没有显示,但我无法输入字符(h/l/c)
。另外,我不能问玩家是否想再玩一次?
这就是我所做的:
import java.util.Random;
import java.util.Scanner;
public class NumberGuessingGame {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int number;
int guess = 0;
int min = 0;
int max = 100;
int answer= (min+max);
number = (int) (Math.random() *100 +1);
System.out.println("Guess a number between 1 and 100.");
//Ask user to type higher 'h', lower 'l' and correct 'c'.
System.out.println("Is it " + number + " ?" + " (h/l/c): " );
//
guess = 50;
while (guess <= 7)
{
System.out.println( "It is: " + guess + "?" + "(h/l/c) : " );
//Type 'h' if guess is high, 'l' for low and 'c' for correct.
if(answer == 'h')
{
max = guess -1;
min = 0;
guess = ((max = min)/2) + min;
guess++;
} else if (answer == 'l')
{
max = 100;
min = guess + 1;
guess = ((max+min)/2);
guess++;
} else if (answer == 'c');
}
System.out.println("Great! Do you want to play again? (y/n): ");
if(answer == 'y')
{
System.out.println("Guess a number between 1 and 100.");
//else prompt another question with if else
} else{
System.exit(0);
}
}
}
答案 0 :(得分:0)
如果猜测太低或太高,您的程序不会接受任何用户输入。
你宣布&#34;回答&#34;等式,所以它应该接受一个数字。 答案需要char或String值。
answer = keyboard.nextChar(); //read a char
answer = keyboard.nextLine(); //read a String
我希望这对你有所帮助。