簡體   English   中英

在Java(Eclipse)中將1D字符串數組轉換為2D Char數組的最佳方法

[英]Best Way to Convert 1D String Array to a 2D Char Array in Java (Eclipse)

對於Java中的單詞搜索游戲,我要求用戶輸入任意數量的單詞(如果他們希望停止添加更多單詞,他們將輸入一個'q'),並且此輸入存儲在數組列表中,然后將其轉換為稱為words.一維數組words. 然后,我調用main中的一種方法開始游戲。 這是代碼片段:

 System.out.println("Grid of the game"); for(char[] j : letterGrid) { System.out.println(j); } System.out.println("Search for these words...\\n"); for(String j : words) { System.out.print(j + ", "); } System.out.print("Enter the Word: "); String word = br.readLine(); System.out.print("Enter Row Number: "); int row = Integer.parseInt(br.readLine()); //matching the word using regex Pattern pattern = Pattern.compile(word, Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(letterGrid[row-1]); 

letterGrid是2D字符數組,但在其顯示的行上: Matcher matcher = pattern.matcher(letterGrid[row-1]); 發生錯誤,並說: The method matcher(CharSequence) in the type Pattern is not applicable for the arguments. 我嘗試更改程序並將letterGrid轉換為一維String數組,但此操作正常,但不適用於2D char數組。 我用隨機字母和用戶單詞(水平,垂直或對角線,不向后)填充letterGrid。

我對此一無所知,目前正在尋找解決問題的方法,但我想我也可以在這里提出問題,因為這里的人會提供很好的建議。 任何幫助將不勝感激!

匹配器唯一可接受的參數是字符串,將char轉換為字符串的最快方法是:

char c = 'a';
String s = String.valueOf(c);  

因此,您可以這樣做:

String s = String.valueOf(letterGrid[row-1]);
Matcher matcher = pattern.matcher(s);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM