我正在尝试在java中编写具有以下输出的java代码。
---JGRASP exez: java Guess Is the number 50? H Ia the number 75? L Is the number 62? L Is the number 56? L Is the number 53? L Is the number 51? C It took me 6 guesses! ---JGRASP: operation complete.
正如你所看到的那样,它总是减少一半。我花了好几个小时试图找出它没有结果。如果你至少可以给出一个提示,我真的很感激。这是我尝试编写代码的不成功。
import java.util.Scanner;
public class GuessNumber
{
public static void main(String[]args)
{
int num1 = 0,num2 = 100,guesses = 0;
String answer;
boolean correct = false;
Scanner keyboard = new Scanner(System.in);
do{
System.out.print("Is the number " + <?> + "? "); //have no idea
answer = keyboard.next();
if(answer.equalsIgnoreCase("C")) {
correct = true;
guessses++;
}
else if(answer.equalsIgnoreCase("H")){
? = (num1 + num2) / 2; //lost here
guesses++;
}
else if(answer.equalsIgnoreCase("L")){
? = (num1 + num2) / 2; //lost here
guesses++;
}
}while(correct == false);
System.out.print("It took me " + guesses + " guesses!");
}
}
答案 0 :(得分:0)
public static void main(String[]args)
{
Random randomNumber = new Random();
int num1 = 0,num2 = 100,guesses = 0, guess=0;
String answer;
boolean correct = false;
Scanner keyboard = new Scanner(System.in);
do{
guess=randomNumber.nextInt(num2-num1) + num1;
System.out.print("Is the number " + guess + "? ");
answer = keyboard.next();
if(answer.equalsIgnoreCase("C")) {
correct = true;
guessses++;
}
else if(answer.equalsIgnoreCase("H")){
num1 = guess;
guesses++;
}
else if(answer.equalsIgnoreCase("L")){
num2 = guess;
guesses++;
}
}while(correct == false);
System.out.print("It took me " + guesses + " guesses!");
}
答案 1 :(得分:0)
尝试这一点,它的作用是,虽然答案不正确,但它将采用num1(猜测的最小值)和num2(猜测的最大值)并找到它们的平均值。如果数字高于最新猜测,我们将下限设置为最新猜测,如果数字较低,我们将上限设置为最新猜测。
import java.util.Scanner;
public class GuessNumber{
public static void main(String[]args)
{
int num1 = 0,num2 = 101,guesses = 0, guess=0;
String answer;
boolean correct = false;
Scanner keyboard = new Scanner(System.in);
do{
guess=(num1+num2) /2 > 0? (num1+num2) /2:1;
System.out.print("Is the number " + guess + "? ");
answer = keyboard.next();
if(answer.equalsIgnoreCase("C")) {
correct = true;
guesses++;
}
else if(answer.equalsIgnoreCase("H")){
num1 = guess;
guesses++;
}
else if(answer.equalsIgnoreCase("L")){
num2 = guess;
guesses++;
}
}while(correct == false);
System.out.print("It took me " + guesses + " guesses!");
}
}