Вопрос

I'm having trouble just return the string of the color. For some reason it will not return the num. Not sure if I need to insert the end of the if statement with an else but I feel like that what the catch statement if for.

Main Class

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;

  }
}

Test Class

package edu.computer.test;

public class ComputerTester {
  public static void main(String[] args) {
    Computer a = new Computer();
    a.getProcessor();
  }
}
Это было полезно?

Решение

Your code example works just fine. I added the following line to your test and it printed the colour as expected:

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

Prints blue or red as appropriate.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top