如何使用return语句在java中重复三次。我希望它看起来像“wordwordword”。另外,我如何制作第二个单独的方法,以便每个字母重复3次?所以它看起来像“wwwooorrrddd”这是我到目前为止(我还需要使用return语句)。
public static String repeatText(String text) {
String repeat;
repeat = text;
return repeat + repeat + repeat;
}
答案 0 :(得分: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;
}
答案 1 :(得分: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
答案 2 :(得分:0)
您提供的代码段工作正常;问题很可能与你如何处理返回值有关。 Java不是通过引用传递的,因此传入的String不会更改
(实施例)
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;
}
就制作另一种方法而言,我建议查看String对象和for循环的Java文档。
字符串:http://docs.oracle.com/javase/7/docs/api/java/lang/String.html
For循环:http://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html