2014-12-05 77 views
0

如何在單行中多次打印字符?這意味着我不能使用循環。我想多次打印" _"打印字符多次

這個方法我試過,但它不工作:

System.out.println (" _" , s); 

s是可變的。

+6

'System.out.println('_____');';-) – ceejayoz 2014-12-05 18:51:12

+0

養成檢查API的習慣。我在[System.out的Java 7 API文檔](http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#out)中沒有看到此方法的示例。 – jdv 2014-12-05 18:54:15

+0

「這意味着我不能使用循環。」怎麼會這樣? – user4235730 2014-12-05 19:03:56

回答

2

您可以在System.out.print(" _");的同一行中打印,以便您可以使用循環。 print而不是println不會追加新的行字符。

for (int i=0; i<5; i++){ 
    System.out.print(" _"); 
} 

將打印:_ _ _ _ _

+1

該帖子狀態沒有循環 – Growler 2014-12-05 18:59:41

+1

我明白,沒有循環條件是需要在同一行打印(println不允許它,但打印)的後果。 – 2014-12-05 19:01:21

+1

非常感謝,它工作完美!^_^ – Econy3 2014-12-08 18:29:33

0

沒有,就像你貼什麼快捷......

那你的意思是「在一個單行」是什麼?

如果一行代碼......看到Mureinik的答案

如果在一行中打印 「_」:

相反:

Print 1 to 10 without any loop in java

System.out.print("_"); 
    System.out.print("_"); 
    System.out.print("_"); 
    System.out.print("_"); 
    System.out.print("_"); 

或者

public void recursiveMe(int n) { 
    if(n <= 5) {// 5 is the max limit 
     System.out.print("_");//print n 
     recursiveMe(n+1);//call recursiveMe with n=n+1 
    } 
} 
recursiveMe(1); // call the function with 1. 
+0

當竊取和修改他人的答案時,更新評論是明智的。遞歸解決方案的第2行應該有註釋'// 5是最大限制' – adamdc78 2014-12-05 18:56:13

+0

System.out。的println(_);是不是一個有效的Java語句:) – jdv 2014-12-05 18:56:24

+0

@ adamdc78編輯上面 – Growler 2014-12-05 18:57:25

3

如果你可以使用外部庫,StringUtils.repeat聽起來您的最佳選擇:

int s = 5; 
System.out.println(StringUtils.repeat('_', s)); 

編輯:
要回答在評論的問題 - 在char要重複和數量 - StringUtils.repeat有兩個參數你想要它的時間,並返回由該重複組成的String。所以,在上面的例子中,它將返回一個由5個下劃線組成的字符串,_____

+0

你能解釋我如何使用StringUtils.repeat? – Econy3 2014-12-09 17:54:35

+0

@ Econy3編輯我的答案與信息 – Mureinik 2014-12-09 18:31:15

2

您可以使用新的Stream API來實現這一點。幕後總是有迭代,但這是一種可能的實現。

Stream.generate(() -> " _").limit(5).forEach(System.out::print); // _ _ _ _ _ 
+0

流API。它永遠不會令我驚歎。 – 2014-12-05 19:03:49

+1

...或者也是'IntStream.range(0,5).forEach(i - > System.out.print(「_」));' – 2016-11-01 21:01:07

0

一次調用打印/的println和使用變量 「s」 -

的System.out.println(Stream.generate(() - > 「_」)的限制(S) .collect(Collectors.joining()))