2016-10-03 47 views
-2

因此对于我的java类,我们必须猜测用户想要的数字,介于0到1024之间。我们必须在10次猜测中猜出数字。我不能在10次猜中得到奇数,我只能在11次得到它们。这是我到目前为止:Java猜谜游戏无法在10次猜测中猜出奇数

import java.util.Scanner;

公共类guessing_game {

public static void main(String[] args) { 
    int high, low, middle; 
    String input; 
    int totalGuesses; 
    high = 1024; 
    low = 0; 
    totalGuesses = 0; 
    String name; 

    System.out.println("What is your name?"); 
     Scanner scan = new Scanner(System.in); 
     name = scan.nextLine(); 

     middle = low + (high - low)/2; 
    System.out.println("Is your number higher than " + middle + ", " + name + "? Please answer 'y' or 'n'. "); 
    System.out.println("If I guess the number, either answer 'that is my number' or answer 'n'."); 
     totalGuesses++; 
     Scanner sca = new Scanner(System.in); 
     input = sca.nextLine(); 

     while (high - low != 1){ 
if (input.equals("y")){ 
      low = middle; 
     middle = low + (high - low)/2; 
    System.out.println("Okay, let's try again."); 
    System.out.println("Is your number higher than " + middle + ", " + name + "? "); 
     input = sca.nextLine(); 
     totalGuesses++;} 
if (input.equals("that is my number")){ 
    System.out.println("Great! Your number is " + middle + ". "); 
    break;} 


else if (input.equals("n")){ 
      high = middle; 
     middle = low + (high - low)/2; 
    System.out.println("Alright, I'll try again."); 
    System.out.println("Is your number higher than " + middle + ", " + name + "? "); 
     input = sca.nextLine(); 
     totalGuesses++;} 
if (high - low == 1){ 
    System.out.println("Number is " + high); 
    break;} 
if (high - low == 2){ 
    System.out.println("Your number is " + high); 
    break;}} 

    System.out.println("This guessing game program used " + totalGuesses + " guesses."); 
    sca.close(); 
    scan.close(); 

    } 

这是对我的代码教授给了我一个Word文档的帮助:

进口java.util.Scanner的;

Start of main method 
    integer high,low,middle; 
    String input; 
    integer totalGuesses; 
    high = 1024; 
    low = 0; 
    totalGuesses = 0; 

    start infinite loop 
     middle = low + (high - low)/2 
     print "Is your number higher than " + middle + " ? (y/n)" 
     increment totalGuesses by 1 
     read from keyboard into input 
     if input is “y” 
      low = middle 
      middle = low + (high - low)/2    
      if (high - low) == 1 
       print "Your number is " + high 
       exit the infinite loop 

     else 
      high = middle 
      middle = low + (high - low)/2 
      if (high - low) == 1 
       print "Your number is " + low 
       exit the infinite loop 



    print "The program used " + totalGuesses + " guesses" 

end of method 

+2

大概的调试器可以帮助你更好。 –

+0

顺便说一下,我可能将“无限循环”解释为“while(True)”, –

回答

1

middle = low + (high - low)/2;的端将无法正确评估是否high - low是奇数。由于除法发生在整数运算中,结果将是截断的