Java循环问题错误地读出

时间:2015-06-17 18:57:11

标签: java

好的,所以我试图获得这个输出: 死0:6个字母 死1:6个字母 等:

现在它打印出Die 0:然后整个读取文件

这是正在进行循环的类,我发布了其他方法,这些方法来自不同的java包。

public void populateDice()
{

    //Loop through the 16 dice times
    for (int row = 0; row < NUMBER_OF_DICE; row++){

    //Create an instance of class Die using the no-argument constructor
        //Die die = new Die();

    //Loop through the 6 sides of the die:
        for (int col= 0; col < NUMBER_OF_SIDES; col++)
        {

            Die die = new Die();
    //Add each of the 6 letters to the die ArrayList representing 
    //the die letters by calling method addLetter in class Die 
           die.addLetter(diceData.get(col).toString());

    //Display the letters of each die by calling method displayAllLetters() in class Die on a separate row
           System.out.println("Die " + row + ":");
           die.displayAllLetters();

    }


    }
   }


public void displayAllLetters()       
{

    try{

    //Loop through all sides of the die and display the data
    for(int x = 0; x < NUMBER_OF_SIDES; x++)
    {
        System.out.println(diceStore.get(x));
    }
    }
    catch(Exception ex)
    {
        System.out.printf("ERROR %s", ex.toString());

    }

}

1 个答案:

答案 0 :(得分:1)

你的代码的结构方式,第一个for循环是die0。一旦你进入内部for循环,你创建你的新Die,添加1个字母,然后告诉它打印所有字母。

我认为您想要的是初始化所有边然后打印字母,因此您将在内部for循环之外使用displayAllLetters()。

 //Loop through the 16 dice times
for (int row = 0; row < NUMBER_OF_DICE; row++)
{

    //Create an instance of class Die using the no-argument constructor
    Die die = new Die();

    //Loop through the 6 sides of the die:
    for (int col= 0; col < NUMBER_OF_SIDES; col++)
    {

        //Die die = new Die(); --- remove this and do it in the above loop ^
        //Add each of the 6 letters to the die ArrayList representing 
        //the die letters by calling method addLetter in class Die 
        die.addLetter(diceData.get(col).toString());

        //Display the letters of each die by calling method    displayAllLetters() in class Die on a separate row
       //System.out.println("Die " + row + ":"); -----move this out of the for-loop
       //die.displayAllLetters(); ----- move this out of the for-loop

    }
    System.out.println("Die " + row + ":");
    die.displayAllLetters();

}