Java 如何使程序吐回任何;如果;按下1或2时的语句?
我试图让程序在按下1或2时打印任何“if”语句,但在按下1或2时也会打印else语句。有人能告诉我我做得不对吗。我会非常感激的 多谢各位Java 如何使程序吐回任何;如果;按下1或2时的语句?,java,Java,我试图让程序在按下1或2时打印任何“if”语句,但在按下1或2时也会打印else语句。有人能告诉我我做得不对吗。我会非常感激的 多谢各位 import java.io.* ; public class MyFan { public static void main(String[] args) { try { InputStreamReader FanSpeed = new InputStreamReader(Sys
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") ;
}
}
}
根据,方法read
返回读取的字符,而不是其数值。也许您可以通过使用
int inputData = strInput.read() - '0';
为了获得期望的结果,我建议对输入进行一些更合适的解析。我可以想象您的读取器正在从
read()
函数返回-1
,或实际字符值(48
,等等),因此,由于是缓冲区的结尾或意外值,因此总是转到else
语句read()
将输出下一个字符值,因此虽然它可以作为int有效,但我会在一些不同的读取器上使用nextInt()
,例如扫描仪
如果继续希望使用BufferedReader,请尝试分析字符:
char next = strInput.read();
int inputData = Integer.valueOf(Character.toString(next)); //Will throw NumberFormatException if not a number
以int
形式获取用户输入的更简单方法是使用扫描仪
:
Scanner scanner = new Scanner(System.in);
int inputData = scanner.nextInt();
BufferedReader::read()
确实返回一个int
,但它表示字符输入,而不是数值。使用Scanner::nextInt()
将返回实际输入的int
。如果输入1或2,是否实际达到了1和2的情况?int-inputData=strInput.read()
可能应该是intinputdata=strInput.readInt()
在您的if
语句中设置一个断点,然后查看inputData
是什么。char-'0'
如何将一个char转换为其数值?@Rogue通常不会;但是,如果char
在“0”、“1”范围内,由于字符在ASCII表中的位置,计算将char
映射到其数值。我承认,这种方法相当粗糙。虽然我曾经尝试过“扫描器”,但我也保留了“BufferedReader”,但它不起作用。我现在将尝试不带BufferedReader的扫描仪,让我看看它提供了什么。谢谢,非常感谢。它成功了,我删除了“try catch”块和“read()”@user3616650太棒了!我很高兴这解决了你的问题。