Java - 我需要将这个字符串打印到一个我可以在循环中使用的字符串

时间:2016-10-16 13:58:36

标签: java for-loop

我已经被埋在这个任务中2天追逐兔子洞以寻找可能的解决方案。我是Java的初学者,所以我相信这不应该像我一样困难。

我试图编写臭名昭着的Java Bean Machine ...我的教授希望Class Path返回一个只保留“R”“L”的字符串变量。代表落球的路径。

每个球应该有自己的路径......我可以获得路径......但是我无法在for / if语句之外的字符串中获得打印路径。

以下是他的指示......如果你能看出我是否错误地解释了这一点。

请帮忙!!提前谢谢您筛选....

我的代码到目前为止********我已更新代码以反映建议..谢谢...... *****************新问题它重复了一行中的一系列字母......我只需要一串6个字母......(LRLLRL)

public class Path {
    StringBuilder myPath;

    public Path() {
        myPath = new StringBuilder();

    }

    void moveRight() {

        myPath.append("R");

    }

    void moveLeft() {
        myPath.append("L");

    }

    public void fallLevels(int levels) {

        levels = 6;

        for (int i = 0; i < (levels); i++) {

            if (Math.random() < 0.5) {
                this.moveRight();

            } else {
                this.moveLeft();

            }

        }

    }
public String getPath() {

    System.out.print(myPath.toString());

    return myPath.toString();

}

}

}         ******谢谢大家..这个班级现在为一个球返回正确的字符串...... ***************

这是我的代码到目前为止多个球...我可以得到一个长连续的6个字符序列的字符串...我需要每个序列是一个可搜索的字符串...我不确定我是否需要更改Path类或者它在simulateGame()方法中的东西。我想我可以在这个驼峰之后接受它......再次感谢你......

public class BeanMachine {
int numberOfLevels;
int[] ballsInBins;
Path thePath = new Path();

public BeanMachine(int numberOfLevels) {
    this.numberOfLevels = 6;
    ballsInBins = new int[this.numberOfLevels + 1];
    // this.numberOfLevels +
}

public void simulateGame(int number) {



    //looping through each ball
for (int i = 0; i < numberOfLevels -1; i++) {
    thePath.fallLevels(0);


        } 
thePath.getPath().toString();

        }             

***这不是这个类的完整代码......我必须让这个方法正确才能继续......

1 个答案:

答案 0 :(得分:0)

您的代码出现问题:

if (Math.random() < 0.5) {
                **loop = this.myPath = "R";**
            } else {
                 **loop = this.myPath ="L";**

            }

将其更改为:

if (Math.random() < 0.5) {
                **loop = this.myPath + "R";**
            } else {
                 **loop = this.myPath + "L";**

            }

添加**以突出显示代码中的错误