Java 使用方法重复字符串
所以我需要编写一个方法,它接受一个字符串对象和一个整数,并重复该字符串乘以整数 例如:重复(“ya”,3)需要显示“YAYA” 我写下了这段代码,但它一个接一个地打印出来。你们能帮帮我吗Java 使用方法重复字符串,java,string,Java,String,所以我需要编写一个方法,它接受一个字符串对象和一个整数,并重复该字符串乘以整数 例如:重复(“ya”,3)需要显示“YAYA” 我写下了这段代码,但它一个接一个地打印出来。你们能帮帮我吗 public class Exercise{ public static void main(String[] args){ repeat("ya", 5); } public static void repeat(String str, int times){ for(i
public class Exercise{
public static void main(String[] args){
repeat("ya", 5);
}
public static void repeat(String str, int times){
for(int i = 0;i < times;i++){
System.out.println(str);
}
}
}
公开课练习{
公共静态void main(字符串[]args){
重复(“是”,5);
}
公共静态void repeat(字符串str,整数倍){
for(int i=0;i
您使用的是System.out.println
,它打印包含的内容,然后是新行。您要将此更改为:
public class Exercise{
public static void main(String[] args){
repeat("ya", 5);
}
public static void repeat(String str, int times){
for(int i = 0; i < times; i++){
System.out.print(str);
}
// This is only if you want a new line after the repeated string prints.
System.out.print("\n");
}
}
公开课练习{
公共静态void main(字符串[]args){
重复(“是”,5);
}
公共静态void repeat(字符串str,整数倍){
for(int i=0;i
您要在新行上打印,请尝试使用以下方法:
public static void repeat(String str, int times){
for(int i = 0;i < times;i++){
System.out.print(str);
}
}
publicstaticvoidrepeat(字符串str,整数倍){
for(int i=0;i
公共级pgm{
公共静态void main(字符串[]args){
重复(“是”,5);
}
公共静态void repeat(字符串str,整数倍){
for(int i=0;i
将System.out.println()更改为System.out.print()
使用println()
的示例:
输出:
hello
hello
hellohello
使用print()
的示例:
输出:
hello
hello
hellohello
试着理解其中的差异
您使用递归/无循环的示例:
public class Repeat {
StringBuilder builder = new StringBuilder();
public static void main(String[] args) {
Repeat rep = new Repeat();
rep.repeat("hello", 10);
System.out.println(rep.builder);
}
public void repeat(String str, int times){
if(times == 0){
return;
}
builder.append(str);
repeat(str, --times);
}
}
将System.out.println
更改为System.out.print
(并在循环后添加一个System.out.println();
)。避免发布代码的可能重复项仅在可能的情况下才回答。告诉OP你的答案如何回答问题,或者他们提供的解决方案有什么问题
public class Repeat {
StringBuilder builder = new StringBuilder();
public static void main(String[] args) {
Repeat rep = new Repeat();
rep.repeat("hello", 10);
System.out.println(rep.builder);
}
public void repeat(String str, int times){
if(times == 0){
return;
}
builder.append(str);
repeat(str, --times);
}
}