从外部类向主函数中提供用户输入

时间:2017-03-16 01:31:37

标签: java

我有两个班级,

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。我该怎么做呢?谢谢。

1 个答案:

答案 0 :(得分:3)

System.inSystem.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);
    }
}