简体   繁体   English

System.err.print和System.out.print的处理差异

[英]Difference in Processing of System.err.print ans System.out.print

Is there a differnece how System.err.print and System.out.print are processed while getting executed? 在执行时如何处理System.err.print和System.out.print有区别吗? I have a twodimensional array of Integers ranged between 2 and 20. The Array is printed as a Matrix and all Integers >=10 shall be printed red, using System.err.print. 我有一个整数数组,其范围是2到20。该数组被打印为矩阵,所有大于等于10的整数都应使用System.err.print打印为红色。 If doing so the output looks like this: 如果这样做,输出如下所示:

 7   11  15  12  12  12  11  16  17  17  13   4   7 
 9    8   4 
 9  
 9    4  10 
12    4  16  12  10 

with all int>=10 being red. 所有int> = 10均为红色。
instead of looking like this 而不是像这样

 11   7   4  15   7 
  9  12   8  12   4 
  9  12  11  16  17 
 17   9   4  13  10 
 12   4  16  12  10   

without the red marks i want. 没有我想要的红色标记。

Both use the same array, first gets printed with this code: 两者都使用相同的数组,首先使用以下代码打印:

public static void printArray2(int ar[][]) {
    if (ar == null)
        System.exit(0);
    for (int i = 0; i < ar.length; i++) {
        for (int j = 0; j < ar[i].length; j++) {
            if (ar[i][j] < 10)
                System.out.print("  " + ar[i][j] + "\t");
            else
                System.err.print(" " + ar[i][j] + "\t");
        }
        System.out.println();
    }
}

while the second output gets printed with this code 而第二个输出使用此代码打印

public static void printArray(int ar[][]) {
    if (ar == null)
        System.exit(0);
    for (int i = 0; i < ar.length; i++) {
        for (int j = 0; j < ar[i].length; j++) {
            if (ar[i][j] < 10)
                System.out.print("  " + ar[i][j] + "\t");
            else
                System.out.print(" " + ar[i][j] + "\t");
        }
        System.out.println();
    }
}

Is there way to prevent the unformmated output while still using System.err.print? 有没有办法在仍然使用System.err.print的情况下防止格式错误的输出?

Basically those two streams represent different consoles. 基本上,这两个流代表不同的控制台。

What really happens when you print to them might very much depend on the JVM implementation or the underlying operating system. 当您打印到它们时,实际发生的情况可能很大程度上取决于JVM实现或底层操作系统。

In that sense: your real problem is your assumption that you can use the consoles like this. 从这个意义上说:您真正的问题是您认为可以使用这样的控制台。

The purpose of the error console is: you print important error messages there. 错误控制台的目的是:在其中打印重要的错误消息。 As an alternative approach - check out if you can use some "ncurses" like library for your application (see here as starting point). 作为一种替代方法-检查是否可以为应用程序使用某些“ ncurses”(如库)(请参阅此处作为起点)。 In other words: instead of mis-using stderr like this - look into ways to gain more control over stdout. 换句话说:不要像这样滥用stderr而是要研究获得对stdout的更多控制的方法。 So that you can print in colours on one console , instead of two. 这样您就可以在一个控制台 (而不是两个)上以彩色打印。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM