2016-01-23 48 views
-1

我試圖創建一個使用Java的遊戲,用戶輸入兩個數字來設置一個範圍,並且計算機必須猜測用戶的數字在該範圍內。用戶輸入的範圍之間的計算機猜測數

編輯:對不起,格式糟糕!這是我的代碼。我實際上已經得到它的工作得很好,我唯一的問題是,如果我輸入兩個值,提示時說1200和1400,我腦海中的數字是1337.告訴程序,1300是太低了,那麼1350太高實際上會導致電腦打印1275的第三次猜測。我不知道我怎麼會讓它打印的1300和1350(1325)平均爲3猜測,而不是打印1275

import java.util.Scanner; 

public class GuessingGame { 
    public static void main(String[] args) { 

    Scanner scnr = new Scanner(System.in); 
    int lowerLimit = 0; 
    int upperLimit = 0; 
    int middleNumber = 0; 
    char userInput = 'a'; 
    int almostLower = 0; 
    int almostUpper = 0; 

    System.out.println("Your number is in this range... (enter 2 numbers)"); 
    lowerLimit = scnr.nextInt(); 
    upperLimit = scnr.nextInt(); 
    middleNumber = (lowerLimit + upperLimit)/2; 

    almostLower = lowerLimit + 1; 
    almostUpper = upperLimit - 1; 

    System.out.print("Type 'h' for 'too high', 'l' for 'too low',"); 
    System.out.println(" and 'c' if I got it right."); //line too long 

    do { 
    System.out.println("Is it " + middleNumber + "?"); 
    userInput = scnr.next().charAt(0); 

    if (userInput == 'c') { 
     System.out.println("I always win"); 
     break; 
    } 

    else if (userInput == 'h') { 

     if (middleNumber == almostLower) { 
      System.out.println("Is it " + lowerLimit + "?"); 
      userInput = scnr.next().charAt(0); 

      if (userInput == 'c') { 
      System.out.println("I always win"); 
      break; 
      } 
     } 
     else { 
     middleNumber = calcMidNum(lowerLimit, middleNumber); 
     } 
    } 

    else if (userInput == 'l') { 

     if (middleNumber == almostUpper) { 
     System.out.println("Is it " + upperLimit + "?"); 
     userInput = scnr.next().charAt(0); 

     if (userInput == 'c') { 
      System.out.println("I always win"); 
      break; 
     }    
     } 
     else { 
     middleNumber = calcMidNum(middleNumber, upperLimit); 
     } 
    } 
    } while (userInput != 'c'); 
} 
public static int calcMidNum(int a, int b) { 
    int calcMid = (a + b)/2; 
    return calcMid; 
} 
} 
+4

請張貼相關碼,優選地是[最小,完整的,並且實施例可驗證程序](http://stackoverflow.com/help/mcve ),這裏有你的問題,而不是鏈接。鏈接可能會死亡,鏈接可能包含大型節目,節目太大而無法請求志願者進行審查。您對此要求的遵守情況將不勝感激,並可能幫助您獲得更好更快的幫助。 –

+0

更糟糕的是,您的鏈接是**圖片**,我們無法複製,粘貼並嘗試運行圖片 - 它不會起作用。所以再次,您的代碼格式爲**文本**在這裏與您的問題。 –

+0

欲瞭解更多關於如何改善這個問題和你未來的問題,請通過[旅遊],[幫助]和[如何問一個好問題](http://stackoverflow.com/help/how-to - 問)部分,看看這個網站的工作原理。 –

回答

0

你不調整下限和上限。

嘗試這種情況:

... 
else if (userInput == 'h') { 
    upperLimit = middleNumber; 
... 

... 
else if (userInput == 'l') { 
    lowerLimit = middleNumber; 
... 
+0

謝謝!這工作! – Andy