Skip to main content
gamedev.net
🔒 Locked

[java] newbie java question

Started by ProperFuked 2 replies 750+ views
Original Post
ProperFuked
ProperFuked
well, maybe not so newbie, but anyway.. i have 2 separate classes, class A and class B, both have main methods. when run, class A produces console output. i want to run class A from class B and capture the console output produced by class A into B so that i can use it in B. The output produced by class a is a String, so capturing it into a String in B would suffice. I was wondering if anyone has any ideas on how i would go about doing this?? Please and thank you.
"Oh, Brother", said Pooh as he was frozen in carbonite.
smitty1276
smitty1276
You need the output from A to be generated in some function that returns the output. B can then call that function.

class ClassA{    public static void main(String [] args)    {        System.out.writeln(ClassA.getOutput());    }    public static void getOutput()    {        return "This is my output.";    }}class ClassB{   protected static String capturedOutput;   public static void main(String [] args)   {      ClassA aInstance = new ClassA();      capturedOutput = aInstance.getOutput();   }}
polly
polly
Hi there,
I think that what you might have here is a design problem. Why do both of your classes have a "main" method? Usually programs have only 1 entry point. If you wanted to programmatically use a String object produced by class A in class B, then you could have something like:

public class A{ public String getString(){  return new String("Foobar"); }}public class B{ public static void main(String[] args){   A a = new A();    String str = a.getString();   // Do something with the String }}


In 2 different files called A.java and B.java respectively. Before compiling both and running the main method in class B.

There is no reason for class A to send its String output to the console if the aim is for class B to capture that output as a String.

Jon
ProperFuked
ProperFuked
thanks guys, that helped a lot.

i need two classes because, well, i need two classes, there's not way to get around that.
"Oh, Brother", said Pooh as he was frozen in carbonite.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.