Java 尝试编写一个被调用的方法,并返回一个星号字符串,该字符串的字符数与有边界的字符数相同
新的编码。。到目前为止,我有:Java 尝试编写一个被调用的方法,并返回一个星号字符串,该字符串的字符数与有边界的字符数相同,java,string,Java,String,新的编码。。到目前为止,我有: public class Main { public static void main(String[] args) { String sOS1 = stringOfStars("a"); System.out.println(sOS1); String sOS2 = stringOfStars("Hello, world!"); Sy
public class Main {
public static void main(String[] args) {
String sOS1 = stringOfStars("a");
System.out.println(sOS1);
String sOS2 = stringOfStars("Hello, world!");
System.out.println(sOS2);
String sOS3 = stringOfStars("012345");
System.out.println(sOS3);
}
static String stringOfStars(String a) {
String string = "";
for(int i = 0; i < a.length(); i++)
string = string + "*";
return string;
// NEED ADDITIONAL CODE HERE
}
}
公共类主{
公共静态void main(字符串[]args){
字符串sOS1=stringOfStars(“a”);
系统输出打印LN(sOS1);
stringsos2=stringOfStars(“你好,世界!”);
系统输出打印LN(sOS2);
字符串sOS3=stringOfStars(“012345”);
系统输出打印LN(sOS3);
}
静态字符串(字符串a){
字符串=”;
对于(int i=0;i
我需要的其他条件:
有很多不同的方法可以做到这一点-除了有很多的如果。基本上你需要锻炼-
final int constrained = Math.max(LOWER, Math.min(HIGHER, input));
制作星星——既漂亮又简洁(Java11之前)
使用简单if-else块的解决方案:
static String stringOfStars(String a) {
int count = 3;
final int alen = a.length();
if(alen > 10) { //if more than 10
count = 10;
} else if(alen > 3) { //if between 3 and 10
count = alen;
}
return "*".repeat(count);
}
与onkar ruikar的回答类似:
static String stringOfStars(String a) {
int count = 3;
final int aLength = a.length();
if (aLength > 3) {
count = Math.min(aLength, 10);
}
return "*".repeat(count);
}
另一种方法是使用正则表达式将任何字符替换为星号
static String stringOfStars(String str){
return str.replaceAll(".", "*");
}
您也可以使用
“*”。重复(5)代码>我希望代码的格式与我一直在使用的代码一致。可以用我上面给出的示例代码的方式来解释吗?当然合并两者并不难<代码>返回“*”。重复(Math.max(3,Math.min(10,a.length()))代码>
static String stringOfStars(String str){
return str.replaceAll(".", "*");
}