我试图使程序在按1或2时打印任何“ if”语句,但是即使按1或2时也要打印else语句。有人可以让我知道我做错了什么吗?我真的很感激。
谢谢。
import java.io.* ;
public class MyFan
{
public static void main(String[] args)
{
try
{
InputStreamReader FanSpeed = new InputStreamReader(System.in) ;
BufferedReader strInput = new BufferedReader (FanSpeed) ;
System.out.print("Please enter a number between 1 and 2: ") ;
int inputData = strInput.read();
if(inputData == 1)
{System.out.println(" Fan is turned on to speed of " + inputData);}
else if(inputData == 2)
{System.out.println(" Fan is turned on to the speed of " + inputData);}
else{System.out.println(" Fan not turned; turn the fan on by pressing 1 or 2 ") ;}
}
catch (IOException ioe)
{
System.out.println("You have to turn the Fan on") ;
}
}
}
最佳答案
根据this documentation,方法read
返回读取的字符,而不是其数字值。也许您可以使用来修复此问题
int inputData = strInput.read() - '0';
以达到所需的结果,但是我建议对输入进行一些更适当的解析。