首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2EE开发 >

问个非常初学者级的猜数字有关问题,高人指点

2012-03-15 
问个非常菜鸟级的猜数字问题,高人指点啊直到猜对为止。。。代码如下:public class GuessNum{public static vo

问个非常菜鸟级的猜数字问题,高人指点啊
直到猜对为止。。。
代码如下:


public class GuessNum{
  public static void main(String args[]) throws java.io.IOException{
  int i = 0 ;
  char num = '6';
   
  while(i!=num){
  System.out.println("Please input a mumber between 1 and 10.");
  i = System.in.read();
  if(i==num) System.out.println("You are right!");
  else{
  if(i<num){
  System.out.println("The number is low!");  
  }
  else{
  System.out.println("The number is high!");
  }  
   
  }
   
  }
  }
}
为什么运行结果会是这样啊??为什么后面会多两段啊??
大于6时:
Please input a mumber between 1 and 10.
7
The number is high!
Please input a mumber between 1 and 10.
The number is low!
Please input a mumber between 1 and 10.
The number is low!
Please input a mumber between 1 and 10.

小于6时:
Please input a mumber between 1 and 10.
4
The number is low!
Please input a mumber between 1 and 10.
The number is low!
Please input a mumber between 1 and 10.
The number is low!
Please input a mumber between 1 and 10.


[解决办法]
小伙子,这种基础的东西,看看api就知道了嘛,System.in.read()是读取输入的一个字节,而你输入的是一个字符,占两个字节,所有,你while循环,第一次的i等于输入字符的第一个字节,而这个自己的值不等于num,于是进入下一次循环,i就等于输入字符的第二个字节了,所以,循环执行了两次,当然就打印两次了啊。
你想实现的效果应该用Scanner来做,把你的

Java code
i = System.in.read();
[解决办法]
Integer i = 0;
char num = '6';
@@@@@Scanner sc = new Scanner(System.in);
while (i != num) {
System.out.println("Please input a mumber between 1 and 10.");
@@@@i = sc.nextInt();

这里应该是缓存的问题 具体解决如上所示

[解决办法]
Java code
import java.util.Scanner;public class GuessNum{    public static void main(String args[]) throws java.io.IOException{        int i = 0 ;        //char num = '6'; 要拿i和num比较,最好是让它们类型一样        int num = 6;        Scanner scanner = new Scanner(System.in); //从Scanner而不是直接从System.in读        while(i!=num){            System.out.println("Please input a mumber between 1 and 10.");            //i = System.in.read();            i = scanner.nextInt(); //scanner支持直接读入一个整数            if(i==num) System.out.println("You are right!");            else{                if(i<num){                    System.out.println("The number is low!");                  }                else{                    System.out.println("The number is high!");                }              }        }    }}
[解决办法]
探讨

Java code

import java.util.Scanner;

public class GuessNum{
public static void main(String args[]) throws java.io.IOException{
int i = 0 ;
//char num = '6'; 要拿i和num比较,最好是让它们类型一样……

热点排行