2014-10-20 25 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

相關問題