我正在运行一个二进制搜索程序,如果值是正确的,它将用户输入字符'l'设置为低'h'高,'c'。我的第一个方法返回字符 我的中点方法只读取第一个字符输入。如果我从50开始按'h',中点正确地升高到75,但我无法让程序读取'l'并再次将值降低到50。该程序只读取用户输入的第一个字符,但我需要更新答案中的值。我的while循环是错误的还是我的决定陈述?谢谢。在用户输入范围1到100执行二进制搜索
import java.util.Scanner;
public class PlayGuessingGame {
public static char getUserresponseGuess(){
Scanner scan = new Scanner(System.in);
char guesses = scan.next().charAt(0);
System.out.println("this is the user input " + guesses);
return(guesses);
}
public static int getMidpoint(int low, int high){
int middle;
//the midpoint is high + low divided by 2
middle = (low + high)/ 2;
System.out.println("is it " + middle);
char answer = getUserresponseGuess();
System.out.println("this is the answer " + answer);
//char get_input = getUserresponseGuess();
//System.out.println("this is the output "+ get_input);
while(low <= high){
if(answer == 'h'){
low = middle + 1;
System.out.println("this is low " + low);
middle = (low + high)/2;
char new_answer = getUserresponseGuess();
middle = (low + high)/2;
System.out.println("is it" + middle);
getUserresponseGuess();
}
//the number presented to the user is is too high, the midpoint is high -1
else if(answer == 'l'){
System.out.println("we're in the low portion");
high = middle - 1;
middle = (low + high) /2;
System.out.print("is it " + middle);
middle = (low + high) /2;
}
if(answer == 'c'){
System.out.println("congrats!");
}
return(middle);
}
return(-1);
}
public static void main(String[] args){
getMidpoint(1,100);
}
}
我该如何请求并接受每个输入?我无法弄清楚为什么只有当输入是'h'时才会循环。 – reubs
@reubs这根本没有循环。你只需在'if(answer =='h')'中调用'getUserresponseGuess'两次,给你一个循环的幻觉。但是当你有一个'return'语句时你不能循环。我编辑了一下,你可以在'Evaluate'和'Loop or not?'中看到问题 – AxelH