2016-12-01 133 views
0

我正在搞亂二維數組,並試圖構建一個程序,將字符串放入二維字符數組中,並用隨機字母填充剩餘的空格。我可以盡全力用隨機字符填充數組,但我無法弄清楚如何將字符串存入char數組。這就是我正在考慮以僞代碼解決問題的原因,因爲我無法正確理解這一點。Java:將字符串添加到多維字符數組中

  1. 我救了串到名爲words一個ArrayList(已編碼的這部分)。

  2. 我想去通過每個元素在ArrayList和比較每一個與空間的char數組中可用

  3. 確定它不會去出界,如果添加的長度,並將這些「座標」保存到另一個ArrayList中。

  4. 然後,使用這些座標,我會將這些單詞逐個轉換爲字符,並用它們替換已經在數組中的隨機字符。

這一切對我來說很有意義,我的頭和寫下來(請讓我現在如果事實並非如此),但問題是我不知道如何真正落實「決定在那裏贏得」超越界限「的一部分。具體而言,我不知道如何真正確定數組中的哪些空間太靠近「邊緣」,以便我添加單詞而不會超出界限。

我真的很感謝任何幫助,並對文本牆感到抱歉。謝謝!

編輯:這是我到目前爲止的代碼。正如我之前提到的,我沒有添加我以上面僞代碼寫的部分,因爲我不知道如何。

import java.util.Scanner; 
import java.util.ArrayList; 

public class BuildArray 
{ 
    private char [][]arrayBoard; 
    private int row, col; 
    private String inWord; 
    ArrayList<String> words = new ArrayList<String>(); 

    public void build() 
    { 
     Scanner input = new Scanner(System.in); //takes in user input 

     System.out.println("How many rows?"); 
     row = input.nextInt(); 
     System.out.println("How many columns?"); 
     col = input.nextInt(); 
     input.nextLine(); 

     do{ 
      System.out.println("Add a word to array (quit to stop) >"); 
      inWord = input.nextLine(); 

      if(!inWord.equals("quit")) 
      { 
       words.add(inWord); 
      } 

     }while(!inWord.equals("quit")); 

     fillArray(); 
    } 

    public void fillArray() 
    { 
     arrayBoard = new char[row][col]; 

     for(int rows = 0; rows < board.length; rows++) 
     { 
      for(int cols = 0; cols < board[rows].length; cols++) 
      { 
       arrayBoard[rows][cols] = randomChar(); 
      } 
     } 

    } 

    public char randomChar() 
    { 
     char alphabet[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 
     'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 
     'y', 'z'}; 

     return alphabet[(char)(alphabet.length * Math.random())]; 
    } 
} 
+0

你可以發佈一個輸入字符串在解析前後應該是什麼樣子的例子嗎? ** board **變量是什麼? –

回答

0

我看到你的問題是將字符串中的每個字符放入該2D字符數組中。 那麼,我建議將輸入字符串轉換爲1D字符數組,然後您可以將該1D字符數組中的每個字符添加到2D字符數組中。 嘗試添加這兩種方法給你的代碼,我認爲你需要隨機添加字符串字符到數組中,如果沒有,你可以替換爲二維數組產生隨機索引的部分。

private char[] stringToArray() { 
    // added method to convert input string to char array 
    return this.inWord.toCharArray(); 
} 


    public void fillArrayWithString() { 
    // added method to insert string randomly in the 2D char array 
    int stringArrayLength = stringToArray().length; 
    int iterator = 0; 
    int cols; 
    int rows; 
    while (iterator < stringArrayLength) { 
     rows = (int) (arrayBoard.length * Math.random()); 
     if (rows < arrayBoard.length) { 
      cols = (int) (arrayBoard[rows].length * Math.random()); 
      if (cols < arrayBoard[rows].length) { 
       arrayBoard[rows][cols] = stringToArray()[iterator++]; 
      } 
     } 
    } 
}