[英]How to print the first character in a two dimensional array
我正在嘗試將每個單詞的第一個字符打印到二維數組中。 當我嘗試使用 ZE83AED3DDF4667DEC0DAAAACB2BB3BE0BZ 打印它時出現錯誤。
String [][] manyWords = {
{"red", "bling", "grand"},
{"bridge", "queen", "chair"}
};
System.out.print(manyWords.substring(0, 1));
我收到無法編譯的源代碼錯誤。
你必須使用一些循環(我更喜歡 for-each 而不是 for/while):
for(String[] strArr : manyWords){
for(String str : strArr){
System.out.println(str.substring(0,1);}}
以下代碼應該可以實現您的目標:
public class test{
public static void main(String[] args){
// Declare test array
String [][] manyWords = {
{"red", "bling", "grand"},
{"bridge", "queen", "chair"}
};
// Since it is a 2d array, loop through it with both an x and y coordinate
// Check https://stackoverflow.com/questions/25798958/iterate-through-2-dimensional-array for more info
for (int i = 0; i < manyWords.length; i++){
for (int j = 0; j < manyWords[i].length; j++){
// Set the current character using charAt
char curr = manyWords[i][j].charAt(0);
// Print it out
System.out.println(curr);
} //end inner for
} //end outer for
} //end psvm
} //end class
印刷:
r
b
g
b
q
c
這是 stream 版本:
Stream.of(manyWords).flatMap(Stream::of).map(s -> s.substring(0, 1))
.forEach(System.out::print);
你可以這樣做。 我希望這對你有幫助。
String [][] manyWords = { {"red", "bling", "grand"}, {"bridge", "queen", "chair"} };
for (int i = 0; i < manyWords.length; i++) {
for (int j = 0; j < manyWords[i].length; j++) {
System.out.print(manyWords[i][j].substring(0, 1) + " ");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.