2014-10-20 22 views
1

线我有一个样品java程序如下:Java测试java的输出单个行,而不是通过线

我正在输出为:

public class Test { 

    public static void main(String[] args) { 
     for(int i =0;i<100;i++){ 
     System.out.println("Value:"+i); 
     } 
    } 

} 

我使用下面的命令运行该程序在CMD如下:

Value:1 
Value:2 
.......... 

我要的是输出应该是在一行上,如:

值1

而不是将每个值显示在单独的行上,它应该更改同一行上的打印值,因为它计数。我怎么做?

+0

您可能会检出[jline](http://jline.sourceforge.net/apidocs/index.html),特别是'ConsoleReader.killLine'。 – 2014-10-20 04:06:15

+0

在基于控制台的应用程序中,你无法真正做到你所要求的,而不依赖于Windows中的'cls'等特定于操作系统的命令。也许你可以把它写成一个Swing GUI,并且带有一个JLabel,它的文本不断更新。 – 2014-10-20 19:17:37

回答

2

使用:

String clrCommand = System.getProperty("os.name").contains("Windows")? "cls" : "clear"; 
for(int i =0;i<100;i++){ 
    Runtime.getRuntime().exec(clrCommand); 
    System.out.print("Value:"+i); 
} 

在这种情况下:Runtime.getRuntime().exec("cls")(或 “清除”)清除您的控制台,然后System.out.print("Value:"+i)版画的价值。所以你将只有一行的效果,数字会发生变化。

这不适用于所有系统。如果它不工作,那么最好的解决办法是垃圾邮件的\n符号,它可以是相当沉重的性能

方面
for(int i=0;i<100;i++){ 
    for (int n=0;n<100;n++) { 
     System.out.println(); 
    } 
    System.out.print("Value:"+i); 
} 
+0

所以你的意思是System.out.print(value:+ i),对吗? – androidGenX 2014-10-20 03:27:40

+0

是的,如果你想它是这样的:“价值:1价值:2价值:3”等... – Victor2748 2014-10-20 03:28:42

+0

@ Victor2748我想他想要它像“价值:1”这将改变为“价值:2”上下一轮,但保持在同一条线上。所以这将是一个覆盖的东西。 – 2014-10-20 03:29:36

-3

的“的println”,将字符串,其中“打印”永不后打印一行确实。

公共类的测试{

public static void main(String[] args) { 
     for(int i =0;i<100;i++){ 
      if(i=0){ 
       System.out.print("Value: "+i); 
      }else{ 
       System.out.print(" "+i); 
      } 
     } 
    } 
} 
+5

欢迎来到StackOverflow。请解释此代码如何解决OP所具有的问题。这会为您的答案增加价值并防止它被删除。 – JamesENL 2014-10-20 03:39:06

+0

@JamesMassey [回顾低质量帖子 - 答案没有解释](http://meta.stackoverflow。com/questions/260411/reviewing-low-quality-posts-answers-without-explanation) – bummi 2014-10-20 06:01:58

+0

@JamesMassey好的,我是新来的,不太了解规则。下次我会加上解释和答案。 – 2014-10-24 09:23:38

-1

使用StringBuilder它。

public class Test { 
    public static void main(String[] args) { 
     StringBuilder builder = new StringBuilder(); 
     builder.append("Value -> "); 
     for(int i =0;i<100;i++){ 
      builder.append(i); 
      builder.append(" -- "); // this line is for distinction from other value 
     } 
     System.out.println(builder.toString()); 
    } 
} 
+0

号码应该只来它应该改变像柜台! – androidGenX 2014-10-20 03:57:30

相关问题