-1

I need a method to write to a BufferedReader input from another class.

In class A I use BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); and str = stdin.readLine(); to get input from the user, which then takes this input, formats it and prints it out with System.out.println.

Now I found out that I want to give some input to class A from class B, so that class A can do it's thing and print it out.

Is there a way to do that?

user207421
  • 305,947
  • 44
  • 307
  • 483
BetaLyte
  • 111
  • 10

1 Answers1

1

You could give A two constructors, a default constructor that takes no parameters and then sets up the BufferedInputStream as you do now, and a second constructor that takes an InputStream as a parameter, and in that constructor wrap the InputStream in your BufferedInputStream and use it instead. Then class B could call A's constructor passing its own InputStream into A.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • Yeah, Thilo basically said the same thing - and I've been trying to do that. I've created two methods in class A, one `setInput` for class B to use to set the input string, and a new "main" method, which basically does the same thing as the real main, but just with the input from `setInput`. But my problem here is, that when I try to set the input in class B by `A.setInput("foo bar")`, I get a `non-static method setInput(java.lang.String) cannot be referenced from a static context`-error when compiling. And I can't figure out why! So I wanted to try another way, hoping it was easier. – BetaLyte Nov 26 '11 at 02:07
  • @Hunteren: that's a completely different problem, likely due to your not calling an instance method on its object but on its class. You'll have to show your code for us to show you exactly where your error is and its solution. And Thilo's answer is significantly different then mine. – Hovercraft Full Of Eels Nov 26 '11 at 02:09
  • @ Hovercraft: Well, yeah it is different problem. I just wondered if it was do-able the other way, maybe it was easier. I don't know about showing my code here as it's homework - then I'd need to make some changes first, and right now I don't wanne waste time on that right now. But I would think I run it on its object. In a class B method (a switch statement), I call classA.setInput("foo bar") - and in class A this method is just creating a new instance of itself and calling the other methods in class A. – BetaLyte Nov 26 '11 at 02:22