System.err.print 和 System.out.print 在执行时的处理方式有区别吗? 我有一个范围在 2 到 20 之间的二维整数数组。该数组被打印为矩阵,所有 >=10 的整数应使用 System.err.print 打印为红色。 如果这样做,输出如下所示:
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
所有>=10的int都是红色的。
而不是看起来像这样
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
没有我想要的红色标记。
两者都使用相同的数组,首先使用以下代码打印:
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();
}
}
使用此代码打印第二个输出
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();
}
}
有没有办法在仍然使用 System.err.print 的同时防止未格式化的输出?
基本上这两个流代表不同的控制台。
当您打印到它们时真正发生的情况可能很大程度上取决于 JVM 实现或底层操作系统。
从这个意义上说:你真正的问题是你假设你可以像这样使用控制台。
错误控制台的目的是:在那里打印重要的错误消息。作为替代方法 - 检查您是否可以为您的应用程序使用一些“ncurses”之类的库(请参阅here作为起点)。换句话说:不要像这样错误地使用 stderr - 研究如何获得对 stdout 的更多控制。这样您就可以在一个控制台上进行彩色打印,而不是两个。