从if语句和for循环返回一个字符串

时间:2014-11-17 23:22:37

标签: java string if-statement for-loop return

我有以下代码,而不是使用System.out.println()方法,我需要返回一个包含星形和缺点的字符串,方法与下面的代码相同。

基本上,我不需要在结尾处返回“”,而是需要将星星和短句包含在实际的返回字符串中!

我是Java新手,不知道如何做到这一点。

我很感激任何建议。

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 "";  
    }

1 个答案:

答案 0 :(得分:0)

只需使用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();
    }
}