如何在for循环中为空字符串添加值?

问题描述 投票:0回答:2

我在弄清楚如何将值附加到字符串末尾时遇到了一些麻烦。在给定的代码中,我们将获得一个骰子值,并使用“ *”将其打印出来。例如,值5将在第一行中带有两个* s,在第二行中包含1,在第三行中包含2。为此,我创建了一个for循环,该循环在达到该值时终止,并尝试附加一个空字符串。我不确定如何用每行中一定数量的星星来表示这个骰子。我尝试了其他方法,例如首先找到总价值,然后创建第二个while循环以添加星星,但似乎无法弄清楚。

public String toString() {
    String stars = " ";

    for (int i = 0; i < value(); i++) {
        if (stars.contains("* * *")){
            //next line
        }
        stars += "*";
    }

    System.out.print(stars);
}
java string loops printing contains
2个回答
0
投票

没有必要那样做。您可以创建一种方法来使其打印出来。如:

static void draw(diceValue) {
    if (diceValue == 1) {
        for (int i = 0; i < diceValue; i++){
            System.out.println("*");
        }
    }
}

然后,在main方法中,您将调用此函数(方法)。另外,您的代码中没有看到主要方法。

public static void main(String[] args) {
    draw(1)
}

请注意,1是输入参数或给出的骰子值。


0
投票

如果只想打印骰子值,这是可以帮助您的程序

public static void main(String[] args) {
        int diceValue = 5;
        for(int i=1; i<= diceValue; i++) {
            if(diceValue % 2 != 0) {
                if( i==1 || i%2 == 0 ) {
                    System.out.print("* ");
                }else if(i==diceValue){
                    System.out.print("*");
                }else {
                    System.out.println();
                    System.out.println(" *");
                }
            }else {
                if( i%2 == 0 ) {
                    System.out.println("* ");
                }else {
                    System.out.print("* ");
                }
            }
        }
    }

input: 
DiceValue = 5 

Output:
* * 
 *
* *

input:
DiceValue = 4

Output:
* * 
* * 

这是基于我对您的问题的理解,您希望以色子格式打印输入。

© www.soinside.com 2019 - 2024. All rights reserved.