2016-12-03 107 views
0

特別是如果說ArrayList是由String元素組成的,我想檢查那些Strings中的每個字母。這是我嘗試過,但顯然它不工作:如何檢查ArrayList中的元素是否等於Java中的另一個值?

public void fillBoard() 
    { 
     board = new char[ROW][COL]; 

     for (String s: words){ 

      for(int rows = 0; rows < board.length; rows++) 
      { 
       for(int cols = 0; cols < board[rows].length; cols++) 
       { 
        if(!s.equals(board[rows][cols])) 
        {       
         board[rows][cols] = randomChar(); 
        } 
       } 

      } 
     } 
    } 

我想每個字符在2D陣列相比於Strings組成ArrayList字母。

ArrayListArrayList<String> words = new ArrayList<String>();而且它是由用戶根據提示,當他們進入的話填充。因此,它可以像{「你好」,「再見」,「字」,...}

board是一個二維字符數組,尺寸由用戶輸入

它然後通過隨機字符填充定義通過這種方法:

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())]; 
    } 

} 

的意圖是,char board[][]陣列還可以包含隨機放置的話,並且當板被更新,所有這些都沒有在words ArrayList一個string再次隨機化的部分中的字母,保留用戶輸入的單詞以及放置在數組中的位置,類似於u在每次回合之後在戰列艦計劃中進行登船。

+0

轉換您的字符串轉換成字符數組,然後嘗試進行比較,並通過你的方式是你的完整的字符串二維數組的每個字符比較,其永遠不會使用這個邏輯,比較一行字符串 –

+1

你重新初始化你的char數組,所以它永遠不會工作。提供一些關於輸入數據的更多信息,可能會提供一個樣本,以便我們提供幫助 – Default71721

+0

@ Default71721我添加了一些額外的信息 – Bluasul

回答

1

您是直接字符串以一個字符需要被改變,並期待在下面的步驟比較:

(1)迭代的char陣列的每一行

(2)獲取stringlist

(3)現在橫跨陣列的列迭代並與在string

每個字符比較

(4)在每個步驟中,我都添加了驗證以檢查它們是否具有可比較的長度,如果不是,則可以根據您的要求實際修改它。

您可以參考下面的代碼用內聯註釋:

public static void fillBoard() { 
     int x=2;//change row size accordingly 
     int y=2;//change row size accordingly 
     char[][] board = new char[x][y]; 
     //load the board char array 

     List<String> words = new ArrayList<>(); 
     //load the list 

     //Iterate each row of the char array 
     for(int rows = 0; rows < board.length; rows++) { 
      //Check if list size is correct to compare 
      if(rows >= words.size()) { 
       System.out.println("list size is lower than 
        the array size,can't caompare these rows"); 
       break; 
      } 
      //Get the string from list 
      String s = words.get(rows); 

      //Iterate across the columns and compare with string character 
      for(int cols = 0; cols < board[rows].length; cols++) { 
       //check if string length is comparable 
       if(s.length() != board[rows].length) { 
        System.out.println("list string length is lower 
         than the array string length,can't caompare "); 
        break; 
       } 
       if(s.charAt(cols) != board[rows][cols]) {       
        System.out.println(s.charAt(cols)+" is different !!!"); 
        board[rows][cols] = randomChar(); 
       } 
      } 
     } 
    } 
相關問題