无法从System.in InputStreamReader返回结果

时间:2013-10-03 01:03:00

标签: java inputstreamreader system.in

我很难返回颜色的字符串。由于某种原因,它不会返回num。不确定我是否需要使用else插入if语句的结尾,但我觉得如果为了catch语句是什么。

主类

package edu.computer.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Computer {
  public Computer() {
  }

  public String getProcessor() {
    InputStreamReader in = new InputStreamReader(System.in);
    BufferedReader keyboard = new BufferedReader(in);
    String num = null;
    System.out.println("Type red to print red or blue to print blue");
    try {
      num = keyboard.readLine();
      if (num.equals("red"))
        num = "red";
      if (num.equals("blue"))
        num = "blue";

    } catch (IOException e) {
      System.out.println("Exception occured!");
    }
    return num;

  }
}

测试类

package edu.computer.test;

public class ComputerTester {
  public static void main(String[] args) {
    Computer a = new Computer();
    a.getProcessor();
  }
}

1 个答案:

答案 0 :(得分:1)

您的代码示例运行正常。我在测试中添加了以下行,并按预期打印颜色:

public static void main(String[] args) {
  Computer a = new Computer();
  System.out.println(a.getProcessor());
}

视情况打印bluered