【发布时间】:2017-02-20 10:41:00
【问题描述】:
我正在运行一个二进制搜索程序,该程序将用户输入字符“l”用于低“h”用于高,如果值正确则使用“c”。我的第一个方法返回字符 我的中点方法只读取第一个字符输入。如果我从 50 开始并按“h”,则中点正确升高到 75,但我无法让程序读取“l”并将值再次降低到 50。该程序仅读取用户输入的第一个字符,但我需要更新答案中的值。我的 while 循环是错误的还是我的决策语句?谢谢你。
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);
}
}
【问题讨论】: