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.
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!");
}
}
}
}
}
------解决方案--------------------