Java是否提供了重复字符串的方法?

时间:2022-04-16 20:46:42

I have a variable:

我有一个变量:

String title = "titleHere";

How would I print the name out three times instead of writing

如何打印出三次而不是写字

System.out.println(title);
System.out.println(title);
System.out.println(title);

or using a for loop?

或使用for循环?

For example, Ruby lets you write title * 3 and Perl lets you write title x 3, so does Java have this too?

例如,Ruby允许你编写标题* 3,而Perl允许你编写标题x 3,那么Java也有吗?

5 个解决方案

#1


1  

Write a [static] utility method that takes a string and an int.

编写一个带有字符串和int的[静态]实用程序方法。

public static void multiPrint(String message, int printCount) {
   for (int i = 0; i < printCount; i++) {
       System.out.println(message);
   }
}

I'd probably put it in a separate class and call that whenever you need the functionality...

我可能会将它放在一个单独的类中,并在需要该功能时调用它...

#2


3  

You can make use of for loop. Just change init condition (i=0) and loop break check (i<3) as per your need.

你可以使用for循环。只需根据需要更改初始条件(i = 0)和循环中断检查(i <3)。

 String title;
    title = "titleHere";


for (int =0;i<3;i++){
 System.out.println(title);

}

#3


1  

add a for loop like

添加一个for循环就好

for(int i = 0; i < no_of_times; i++)
{`
    System.out.println(title);
}`

#4


0  

Well if you're looking for another alternative, you could also use a while loop:

好吧,如果你正在寻找另一种选择,你也可以使用while循环:

String title = "titleHere";

int i = 0;
while (i < 3) {
    System.out.println(title);
    i++;
}

#5


0  

Use a For Loop

使用For循环

String title;
title = "titleHere";
for(int i = 0; i < no_of_times; i++)
{
    System.out.println(title);
}

#1


1  

Write a [static] utility method that takes a string and an int.

编写一个带有字符串和int的[静态]实用程序方法。

public static void multiPrint(String message, int printCount) {
   for (int i = 0; i < printCount; i++) {
       System.out.println(message);
   }
}

I'd probably put it in a separate class and call that whenever you need the functionality...

我可能会将它放在一个单独的类中,并在需要该功能时调用它...

#2


3  

You can make use of for loop. Just change init condition (i=0) and loop break check (i<3) as per your need.

你可以使用for循环。只需根据需要更改初始条件(i = 0)和循环中断检查(i <3)。

 String title;
    title = "titleHere";


for (int =0;i<3;i++){
 System.out.println(title);

}

#3


1  

add a for loop like

添加一个for循环就好

for(int i = 0; i < no_of_times; i++)
{`
    System.out.println(title);
}`

#4


0  

Well if you're looking for another alternative, you could also use a while loop:

好吧,如果你正在寻找另一种选择,你也可以使用while循环:

String title = "titleHere";

int i = 0;
while (i < 3) {
    System.out.println(title);
    i++;
}

#5


0  

Use a For Loop

使用For循环

String title;
title = "titleHere";
for(int i = 0; i < no_of_times; i++)
{
    System.out.println(title);
}