2015-10-18 58 views
-1

我試圖將int更改爲字符串並將其打印爲這樣。如何將int更改爲像這樣的字符串

int count; 
    for(count = 0; count <= 99;count++) 
    System.out.print(count+", "); 
    System.out.print(100); 

它就會像1,2,3,4,5,6,7,8

是被3整除將改爲樹的數字。 如果它可以被5整除,它將是「高」。 5如果它可以被分開,它會很「緊」。

1,2,樹木,4,高,樹,7,8

我卡在如何去改變它。

任何幫助?

+0

在代碼中無法看到樹。你到目前爲止做了什麼來完成它? –

+0

我是初學者,所以我嘗試過。如果(count%number){count = tree)我在網上搜索,不能得到很遠 – INeedHelp

+0

我想也許你需要開始是將一些字符串連接在一起,以使一個更長的字符串。 '「1,2,3,」+ 4「是」1,2,3,4「這會讓你開始。 「替換」部分需要更多的代碼。 – markspace

回答

1

在此基礎上回答下你的意見,你需要更新你的現有代碼,並替換爲以下:

int count; 
    for(count = 1; count <= 99;count++){ 
    if(count%3==0 && count%5==0){ 
     System.out.print("tigh, "); 
    } 
    else if(count%5==0){ 
     System.out.print("high, "); 
    } 
    else if(count%3==0){ 
     System.out.print("tree, "); 
    } 
    else{ 
     System.out.print(count+", "); 
    } 


    } 
    System.out.print(100); 

希望這有助於

+0

最後一個數字(100)和'「tree」+「,」可以替換爲「tree」,'後面不應該有逗號。 –

+0

它的工作,但我也需要通過5 disvible它是高的,如果它是3和5整除它是緊的。我嘗試過自己,但它會重複這些數字。 – INeedHelp

+0

@FernandoMatsumoto謝謝。更新它。 –

0
for (int i =0; i <= 99; i++) { 
    if (i % 3 == 0) 
     System.out.print("tree, "); 
    else 
     System.out.print(i + ", "); 

} 
+0

儘管這可能會回答這個問題,但是對於發生了什麼變化的一些解釋以及爲什麼可能比裸露的代碼更有幫助。此外,這實際上並沒有解決大部分問題。 – CollinD

0

試試這個,這是一個有點複雜,但我想成爲獨一無二的:

for (int count = 0; count <= 99; count++) { 
    System.out.print(count % 3 == 0 && count % 5 == 0 ? "tigh, " : (count % 3 == 0 ? "tree, " : (count % 5 == 0 ? "high, " : count + ", "))); 
} 
System.out.println(100); 
+0

在100之後不應該有逗號。這就是爲什麼它在OP代碼中單獨的'System.out.print(100)''語句中出現循環。此外,輸出應該是在一行而不是100行(用'print'替換'println')。 –

+0

哎呀,謝謝! – RobertR

+0

如果想要,適當的格式化可以使重新插入的格式變得很長。 – Deduplicator

2

從你對@ BalwinderSingh的評論,它se ems類似於FizzBu​​zz。這裏是我會怎麼做:

for (int i = 0; i < 100; i++) { 
    if (i % 15 == 0) { // % 3 && % 5 
     System.out.print("tigh, "); 
    } else if (i % 5 == 0) { 
     System.out.print("high, "); 
    } else if (i % 3 == 0) { 
     System.out.print("tree, "); 
    } else { 
     System.out.print(i + ", "); 
    } 
} 
System.out.print(100); 
+1

這會遺漏其他人,只會打印樹/高 – INeedHelp

+0

@INeedHelp爲什麼?那麼它將不符合要求。 – TheCoffeeCup

+0

@MannyMeng你的代碼不打印正常數字。其他場景 –

0

還是這樣

System.out.println(IntStream.rangeClosed(0, 100) 
      .mapToObj(i -> i % 15 == 0 ? "tigh" 
          : i % 5 == 0 ? "high" 
          : i % 3 == 0 ? "tree" 
          : String.valueOf(i)) 
      .collect(Collectors.joining(", "))); 

(不Eclipse中,由於它似乎是一個錯誤編譯:http://ideone.com/KZ79pk作品)

順便說。 100可以被3和5整除。所以,如果你作弊,不要println(100) :)

相關問題