[英]Returning a string from a if-statement and for-loop
I have the following code and instead of using the System.out.println() method, I need to instead return a string that includes stars and minuses in the same way that the code below does. 我有以下代码,而不是使用System.out.println()方法,而是需要返回一个包含星号和负号的字符串,其方式与下面的代码相同。
Essentially, instead of just returning the "" at the end, I need the stars and minuses to be included in the actual return string itself! 本质上,我需要在实际的返回字符串本身中包含星号和减号,而不仅仅是在末尾返回“”!
I am very new to Java and have no idea of how to do this. 我对Java非常陌生,不知道如何执行此操作。
I would appreciate any advice. 我将不胜感激任何建议。
public static String starMinusLine(int stars, int minuses){
if(minuses ==1){
for (int j= 0; j< stars; ++j){
System.out.print("*");
}
for (int i = 0; i < (minuses); ++i){
System.out.print("-");
}
}
if (minuses % 2 == 0){
for (int i = 0; i < (minuses*0.5); ++i){
System.out.print("-");
}
for (int j= 0; j< stars; ++j){
System.out.print("*");
}
for (int k=0; k < (minuses*0.5); ++k){
System.out.print("-");
}
}
if (minuses % 2 == 1 && minuses != 1){
for (int i = 0; i < ((minuses*0.5)-0.5); ++i){
System.out.print("-");
}
for (int j= 0; j< stars; ++j){
System.out.print("*");
}
for (int k=0; k < ((minuses*0.5)); ++k){
System.out.print("-");
}
}
return "";
}
Just use StringBuilder to build up the string as you go: 只需使用StringBuilder即可构建字符串:
public static String starMinusLine(int stars, int minuses) {
StringBuilder sb = new StringBuilder();
if (minuses == 1) {
for (int j = 0; j < stars; ++j) {
sb.append("*");
}
for (int i = 0; i < (minuses); ++i) {
sb.append("-");
}
}
if (minuses % 2 == 0) {
for (int i = 0; i < (minuses * 0.5); ++i) {
sb.append("-");
}
for (int j = 0; j < stars; ++j) {
sb.append("*");
}
for (int k = 0; k < (minuses * 0.5); ++k) {
sb.append("-");
}
}
if (minuses % 2 == 1 && minuses != 1) {
for (int i = 0; i < ((minuses * 0.5) - 0.5); ++i) {
sb.append("-");
}
for (int j = 0; j < stars; ++j) {
sb.append("*");
}
for (int k = 0; k < ((minuses * 0.5)); ++k) {
sb.append("-");
}
}
return sb.toString();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.