2014-12-04 47 views
-1
public static void main(String[] args) throws IOException { 

    System.out.println("Hello, come and play a game with me!"); 

    int x = 5; 
    int guess; 

    do { 
     System.out.println("Please input a number..."); 
     guess = System.in.read(); 
     guess = System.in.read(); 
     if (guess < 5) { 
      System.out.println("You guessed the number!"); 
      break; 
     } 
    } while (guess > 5); 
} 

所以这里我写了一些代码。它应该是一个猜谜游戏,但无论我输入什么内容,它总是会在输出中输入“请输入一个数字......”不管我放哪个。基本上,如果“猜测”超过5,那么他们猜对了数字。如果不是,那么他们没有猜到这个数字。这是游戏的前提。有人可以帮我修复我的代码,所以不管输出什么都不一样吗?为什么这个do-while循环没有产生正确的输出?

+0

您是否尝试调试以查看'guess'在执行过程中有哪些值? – 2014-12-04 16:09:01

+0

1)你为什么要求猜测输入两次?也看看你的if语句,如果猜测小于5,那么你打破了 – 2014-12-04 16:11:01

+0

看看这个http://stackoverflow.com/questions/15273449/what-does-system-in-read-actually-return – Karunakar 2014-12-04 16:12:18

回答

3

System.in.read();给你char。所以当你输入“1”时,它会给你它的字符值49,所以你不能输入数字来输入整数5。所以改变你的阅读方法。你可以使用Scanner

+0

是的,你是正确的.. :) – Karunakar 2014-12-04 16:11:33

+0

这解决了我的问题!我使用了Rami的代码,并用Scan扫描取代了缓冲区,它的功能就像我知道的格式和代码的魅力!感谢大家! – 2014-12-04 16:31:07

1

你正在做的相反 - 小于5的答案被接受为正确的。

0

这里是你的代码的工作版本。

正如在以前的答案中所述,System.in读取字符,因此您不能直接读取数字。下面的代码利用了适用于InputStream的BufferedReader API。

public class App { 


     public static void main(String[] args) throws IOException { 

       System.out.println("Hello, come and play a game with me!"); 

       int x = 5; 
       int guess; 

       do     
       {    
        System.out.println("Please input a number..."); 
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 

        guess = Integer.parseInt(br.readLine()); 
        if(guess < 5){ 

         System.out.println("You guessed the number!");      
         break;      
        } 

       } while(guess>5);   
     }  
    } 
0

看起来你没有使用变量x,请尝试使用扫描仪类从用户那里得到输入

公共静态无效的主要(字串[] args)抛出IOException异常{

System.out.println("Hello, come and play a game with me!"); 
int guess; 
Scanner input = new Scanner(System.in); 



do { 
    System.out.println("Please input a number..."); 
    guess = input.nextInt(); 
      if (guess < 5) { 
     System.out.println("You guessed the number!"); 
     break; 
    } 
} while (guess > 5); 

}

相关问题