繁体   English   中英

当按下1或2时,如何使程序吐出任何“if”语句?

[英]How to make the program spit-back any of the “if” statements when 1 or 2 is pressed?

我正在尝试让程序在按下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") ;
        }

      }

}

根据此文档read方法返回字符读取,而不是其数值。 也许你可以通过使用修补这个

int inputData = strInput.read() - '0';

为了达到预期的效果,我建议对输入进行更合适的解析。

将用户输入作为int的更简单方法是使用Scanner

Scanner scanner = new Scanner(System.in);
int inputData = scanner.nextInt();

BufferedReader::read()确实返回一个int ,但它表示字符输入,而不是数值。 使用Scanner::nextInt()将返回输入的实际int

我想你的读者从read()函数返回-1或实际字符值( 48等),因此总是转到else语句,因为它是缓冲区或意外值的结束。 read()将输出下一个字符值,因此虽然它可以作为int有效,但我会在某些不同的读取器(如Scanner nextInt()上使用nextInt()

如果您继续想要使用BufferedReader,请尝试解析该字符:

char next = strInput.read();
int inputData = Integer.valueOf(Character.toString(next)); //Will throw NumberFormatException if not a number

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM