2015-06-17 54 views
-1

好了,所以我試圖讓這個輸出: 晶粒0:6個字母 芯1:6個字母 等:Java的循環問題,讀出正確

而現在它打印出晶粒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()); 

    } 

} 
+0

很難跟隨哪裏。請顯示一個簡短的*完整的*程序來證明問題。 (特別不清楚爲什麼你有一個名爲'Die'的類'Class'的變量,順便說一下......) –

+0

我給你整理了一下 – codegeek123

+0

這還不是一個簡短但完整的程序。首先是一個方法聲明,一方面... –

回答

1

您的代碼結構化的方式,第一個for循環是die0。一旦你到達內循環,你就可以創建新的Die,添加1個字母,然後告訴它打印所有的字母。

我想你想要的是初始化所有的邊,然後打印字母,所以你會有displayAllLetters()以外的內部for循環。

//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(); 

}