Java 从外部类在主函数中输入用户输入
我有两门课Java 从外部类在主函数中输入用户输入,java,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()
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.
}
}
我从Class2运行main,必须将值(4个整数)输入System.in中的Scanner。我该怎么做呢?谢谢。通过
System.setIn()
将System.in
设置为另一个输入流,然后从class2
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);
}
}
看@ScaryWombat没有错误,但我只是不知道该怎么做。控制台要求输入4个整数,但我一直在想如何从Class2输入。Class2的
code
代码有什么问题?对我来说很有用-投票结束我们不知道他的情况或问题,即使这不是最好的做法,但我认为@Steven的问题很清楚,可以回答。谢谢。工作得很好。