2014-02-18 191 views
-2

我如何讓一個單詞在java中用return語句重複三次。我希望它看起來像「wordwordword」。另外我將如何製作第二種單獨的方法,以便每個字母重複3次?所以它看起來像「wwwooorrrddd」這是我到目前爲止(我也需要使用返回語句)。如何讓單詞重複?

public static String repeatText(String text) { 
String repeat; 
repeat = text; 
return repeat + repeat + repeat; 
} 
+2

即代碼看起來細用於重複的詞;它不工作? –

+0

這段代碼有什麼問題? – Mauren

+0

@Mauren它不會做「wwwooorrrddd」:) – user2864740

回答

0
public static void main(String[] args) 
{ 
    System.out.println(repeatText("bar")); 
    System.out.println(changeText("bar")); 
} 

public static String repeatText(String text) 
{ 
    String temp = ""; 

    for(int i = 0; i < text.length(); i++) 
     temp += text; 

    return temp; 
} 

static String changeText(String text) 
{ 
    String temp = ""; 

    for(int i = 0; i < text.length(); i++) 
     for(int j = 0; j < text.length(); j++) 
      temp += text.substring(i, i + 1); 

    return temp; 
} 
0

你可以做,

public static String repeatText(String text, 
    int count) { 
    // return text + text + text; 
    StringBuilder sb = new StringBuilder(); 
    for (int i = 0; i < count; i++) { 
    sb.append(text); 
    } 
    return sb.toString(); 
} 

public static String repeatLetters(String text, 
    int count) { 
    StringBuilder sb = new StringBuilder(); 
    for (char c : text.toCharArray()) { 
    for (int i = 0; i < count; i++) { 
     sb.append(c); 
    } 
    } 
    return sb.toString(); 
} 

public static void main(String[] args) { 
    System.out.println(repeatText("word", 3)); 
    System.out.println(repeatLetters("word", 3)); 
} 

它打印

wordwordword 
wwwooorrrddd 
+0

YaY !!!你救了我!非常感謝! – user3290671

0

的代碼片段您提供精美作品;這個問題很可能與你如何處理返回值有關。 Java的沒有被引用,因此字符串傳遞將不會改變通過

(前)

public static void main(String[] args){ 
    String text = "word"; 
    String newText = ""; 
    repeatText(text); // this is probably how you're calling it which is why it's not working 
    newText = repeatText(text); // this is how you should be calling it retain the value; 
} 

至於使其他方法我建議看Java文檔的String對象,並for循環。

字符串:http://docs.oracle.com/javase/7/docs/api/java/lang/String.html

For循環:http://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html