2017-10-08 80 views
-1

我有一個非常奇怪的陣列打印。代碼和輸出如下。
非常奇怪的陣列打印

public class AdvDotComLauncher { 
    public static void main(String[] args) { 
     AdvDotComTable table = new AdvDotComTable(); 
     table.createTable(5,5, 5); 
    } 
} 

代碼與以下問題陣列。

import java.util.ArrayList; 


public class AdvDotComTable { 
    public void createTable(int size, int dotComAmount, int dotComSize) { 
     //Holds the DotComs that will be randomly put onto the map 
     String[] dotComs = {"Pets.com", "Amazon.com", "Target.com", "Apple.com", "Microsoft.com", "Steampowered.com"}; 
     //Holds the rows and columns 
     ArrayList<Character> row = new ArrayList<Character>(); 
     ArrayList<Integer> column = new ArrayList<Integer>(); 
     column.add(0); 
     char[] theAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray(); 
     //Makes sure the Dot Coms will fit 
     if (dotComAmount >= dotComs.length || dotComAmount/dotComSize > size) { 
      System.out.println("There are too many dot coms! Please enter different amounts."); 
     } 
     //Used in the while loop to make sure that the correct amount of columns are created 
     int done = size * size; 
     //Used to get an index value in theAlphabet 
     int theAlphabetIndex = 0; 
     //Used to add columns 
     int number = 0; 
     //Used to tell when to create a column 
     int size2 = size; 
     //Starts creating rows and columns 
     while (done > 0) { 
      row.add(theAlphabet[theAlphabetIndex]); 
      if (size2 == 0) { 
       size2 = size; 
       column.add(number); 
       number++; 
       theAlphabetIndex++; 
      } 
      System.out.println(row.get(number) + "" + column.get(number)); 
      size2--; 
      done--; 
     } 
     System.out.println("The table has been created with " + dotComAmount + " Dot Coms, a table size of " + size + ", and a Dot Com size of " + dotComSize + "."); 
    } 
} 

輸出:

A0 
A0 
A0 
A0 
A0 
A0 
A0 
A0 
A0 
A0 
A1 
A1 
A1 
A1 
A1 
A2 
A2 
A2 
A2 
A2 
A3 
A3 
A3 
A3 
A3 
The table has been created with 5 Dot Coms, a table size of 5, and a Dot Com size of 5. 

的預期結果是這樣的:

A0 
B0 
C0 
D0 
E0 
A1 
B1 
C1 
D1 
E1 
A2 
B2 
C2 
D2 
E2 
A3 
B3 
C3 
D3 
E3 
A1 
B4 
C4 
D4 
E4 

我不知道是什麼原因造成這個問題,任何幫助,將不勝感激。

+0

[什麼是調試器,它如何幫助我診斷問題?](https://stackoverflow.com/q/25385173/5221149)---迄今爲止我們可以給你的最好的幫助是建議你學習如何調試代碼,這樣你就可以自己發現問題,而不必等待其他人爲你調試。你也學到更多。 – Andreas

+0

我可以通過換行'column.add(number);' 和'number ++;'來修正數字。不過,我對你試圖用字母做什麼感到困惑。 –

回答

0

查看程序再次theAlphabetIndex永遠不會增加,可以將其設置爲0,但它不會增加爲size2值爲5. theAlphabetIndex=0你只得到A(..)是在0指數。

+0

你錯了。我把一個System.out.println(「測試」); if語句內部的語句,並將其打印出來。而且,每當循環經過時,size2都會減少... – Lyfe

+0

那麼爲什麼你會得到a0(10次),a1(5次)等等。只有你的while循環正常運行25次。 –