当前位置:   article > 正文

int a = 10; int b = 20;method(a, b);//需要在method方法被调用之后,仅打印出a=100,b=200,请写出method方法的代码_public class abc { static int a = 10 , b = 20 ; pu

public class abc { static int a = 10 , b = 20 ; public static void main(

最近网上比较【风骚】的一道面试题,大概题目是这样的:

这里写图片描述

乍一看,认为张手就可以写出来,不过仔细一想,不是那么回事。好了,不说了, 直接上答案,目前有两种,一种是终止JVM,另一种是改变打印输出流。

    public static void main(String[] args) {
        int a = 10;
        int b = 20;

        method(a, b);

        System.out.println("a="+a);
        System.out.println("b="+b);
        tes();
    }
    //方法1
    public static void method(int a,int b) {
        System.out.print("a=100 b=200");
        System.exit(0);
    }
    //方法2
    public static void method(final int a,final int b) {
        PrintStream stream = new PrintStream(System.out){
            @Override
            public void print(String s) {
                super.print(s.replace(a+"", a*10+"").replace(b+"", b*10+""));
            }
        };
        System.setOut(stream);
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

这尼玛分明就是一道脑筋急转弯啊!!!

PrintStream 是打印输出流,它继承于FilterOutputStream。
PrintStream 是用来装饰其它输出流。它能为其他输出流添加了功能,使它们能够方便地打印各种数据值表示形式。

特殊的PrintStream:
System.in ———— 关键是已经打开
public static final InputStream in“标准”输入流。此流已打开并准备提供输入数据。通常,此流对应于键盘输入或者由主机环境或用户指定的另一个输入源。

System.out
public static final PrintStream out“标准”输出流。此流已打开并准备接受输出数据。通常,此流对应于显示器输出或者由主机环境或用户指定的另一个输出目标。

System.err
public static final PrintStream err“标准”错误输出流。此流已打开并准备接受输出数据。
通常,此流对应于显示器输出或者由主机环境或用户指定的另一个输出目标

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/940389
推荐阅读
相关标签
  

闽ICP备14008679号