直到猜对为止。。。
代码如下:
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!"); } } } }}
------解决方案--------------------