今天android的一个群里在讨论一个java的面试题,如下:
class test
{
public static void main(String []args){
int a=10,b=10;
Method(a,b);
System.out.println("a="+a);
System.out.println("b="+b);
}
}
实现Method方法,要求输出,a=100,b=200。
刚看到这个题目我一蒙,这个什么写啊,java又没有指针什么的。
一会儿有一位神人发出了答案:
public static void Method(int a,int b)
{
System.out.println("a=100");
System.out.println("b=200");
System.exit(0);
}
佩服、佩服,这样却是实现了题目的要求。但是这应该不是这条题目的本意,真正要考的是输出重定向的问题。正确答案如下:
public static void Method(int a,int b){
PrintStream ps = new PrintStream(System.out){
@Override
public void println(String x) {
if(x.startsWith("a")) super.println("a=100");
if(x.startsWith("b")) super.println("b=200");
}
};
System.setOut(ps);
}
所以这条题目的要点在于java的输出重定向的问题,不仅输出可以重定向,输入也可以重定向。