【问题标题】:Program provides correct output for println(String s); but not print(String s); why?程序为 println(String s) 提供了正确的输出;但不是 print(String s);为什么?
【发布时间】:2013-03-04 15:02:18
【问题描述】:

以下是我遇到问题的代码:

public class testOutput {

    public static void main(String[] args) throws Exception {

        int count = 50000;
        String s = "Vinjith";

        for(int i=0;i<count;i++) {
            System.out.print(s);  // change this to println(s); and it works! 
            System.out.flush();
        }
    }

}

我正在使用 Eclipse Galileo - jdk 1.6/jre6。

  • 我没有对控制台输出设置任何限制。
  • 我也用 BufferedWriter 尝试过相同的程序:不起作用
  • 当变量count = 584; 不超过这个值时它可以工作。
  • 当我使用 System.out.print(s) 时,我没有得到任何输出;但是当我使用 System.out.println(s);我得到了 50000 行字符串“Vinjith”。

谢谢。

【问题讨论】:

  • System.out.println() 的行为类似于System.out.print,唯一的区别是在打印后会添加换行符。一种或另一种的使用取决于您的需求(这将定义输出是否有效)。
  • 您必须准确指定 什么 不起作用。
  • 如果您将OutputStream 用于System.out,会发生什么情况?
  • okie .. 经过一些研究 - 这是一个现有的错误 - bugs.eclipse.org/bugs/show_bug.cgi?id=19850 .. 如果你需要打印它 - 将固定宽度控制台 -> 最大字符宽度设置为 1000 或任何你的 Eclipse 版本支持..

标签: java eclipse string printing


【解决方案1】:

这是因为同一行上有太多字符,而 Eclipse 在其控制台上不支持该字符(您将在控制台上看不到任何打印内容)。在命令行上尝试相同的代码,它应该可以工作。

【讨论】:

  • Eclipse 说它最多可以打印 1000000 个字符(在 Windows->preference->run->console 中找到)。它几乎不能在一条直线上打印 5000 个字符。
  • 他的限制达到 585 即 count>585 .. eclipse 不打印任何东西
【解决方案2】:

这是因为您在 Eclipse 控制台上打印的字符长度超出了限制。

试试这个,看看能不能打印出来。

System.out.print(s);  // change this to println(s); and it works!
System.out.println();
System.out.flush();

另外,关于限制问题,试试这个。在preferences -> run/debug -> console中,会有一个名为Fixed Width Console的复选框。它的最大限制是1000。尝试将其设为1000 并运行您的原始代码,如下所示。你会看到它打印了一些字符,其余的则抛出一个Internal Error

System.out.print(s);  // change this to println(s); and it works!
System.out.flush();

【讨论】:

  • @vj07 - 如果您仔细观察,更改 Fixed Width Console 后的每一行正好有 1000 个字符。
【解决方案3】:

你试过了吗:

    for(int i=0;i<count;i++) {
        System.out.print(s);  // change this to println(s); and it works! 
    }
    System.out.println("---done");
    System.out.flush();

当您尝试计数值(100、500、1000、2000、10000 等)时会发生什么?

请发布它何时工作的输出以及“计数”是什么。

我之前研究过flush() 的问题,它归结为您的操作系统如何在内部处理缓冲区。大多数 JRE 只定义接口,然后依赖操作系统来实现实际行为,在某些情况下它会变得很奇怪。 See my answer 一个类似的问题。

【讨论】:

  • 打印;和 println(s);适用于最多 584 的计数。之后打印;不起作用。但 println(s) 有效。打印输出:VinjithVinjithVinjith..... for println(s);是字符串之间的新行。
  • 发布了另一个版本供您尝试。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-25
  • 2012-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多