1

I have two classes,

public class ClassOne {

static Scanner sc;
static int a,b,c,d;

public static void main(String [] args){
    sc = new Scanner(System.in);

    System.out.println("Input 4 numbers, one after another");
    a = sc.nextInt();
    b = sc.nextInt();
    c = sc.nextInt();
    d = sc.nextInt();

    System.out.println(a + b + c + d);
}

}


public class ClassTwo {

public static void main(String [] args){
    ClassOne.main(null);

    // I want to programatically input 
    // numbers into the Scanner from ClassOne,
    // and run the program.

    }
}

I'm running main from ClassTwo, and must feed in values (4 integers) to Scanner in System.in. How can I go about doing this? Thank you.

Steven
  • 604
  • 6
  • 11
  • see http://stackoverflow.com/questions/283816/how-to-access-java-classes-in-the-default-package – Scary Wombat Mar 16 '17 at 01:35
  • @ScaryWombat there are no errors, but I just have no idea on how to go about this. The console requests for 4 integers, but I'm stuck on how to feed it in from ClassTwo. – Steven Mar 16 '17 at 01:36
  • what is wrong with the `ClassTwo` code? – Scary Wombat Mar 16 '17 at 01:38
  • @ScaryWombat there is nothing wrong, however it doesn't do anything. I wish to programatically feed in 4 integers from ClassTwo into the System.in. – Steven Mar 16 '17 at 01:40
  • 1
    works for me - vote to close – Scary Wombat Mar 16 '17 at 01:41
  • @ScaryWombat - yes it works, however does not work as intended. I wish to figure out a way to PROGRAMATICALLY!!!!!!!! (not typing into console) write to System.in from ClassTwo. – Steven Mar 16 '17 at 01:43
  • It works for me as well.. If it's not working, please share the error/screen shot – rpfun12 Mar 16 '17 at 01:45
  • 1
    We don't know his situation or problem and even if it is not the best practice to do but I think @Steven 's question is quite clear and answerable. – Huy Le Mar 16 '17 at 02:06
  • @ScaryWombat I apologize. – Steven Mar 16 '17 at 03:50

1 Answers1

3

Set System.in to another InputStream by System.setIn(<your_input_stream>) then write to that input stream from your ClassTwo

public class ClassTwo {    
    public static void main(String [] args){
        InputStream replacedIn = new ByteArrayInputStream("1\n2\n3\n4\n".getBytes());
        System.setIn(replacedIn);
        ClassOne.main(null);
    }
}
Huy Le
  • 657
  • 5
  • 17