我有两个班级,
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.
}
}
我从ClassTwo运行main,并且必须将值(4个整数)输入System.in中的Scanner。我该怎么做呢?谢谢。
答案 0 :(得分:3)
按System.in
将System.setIn(<your_input_stream>)
设置为另一个InputStream,然后从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);
}
}