我的目标是创建一个字母表的二维数组,如下所示:
ABC
BCA
驾驶室
这样每行和每列都有26个字母。我知道我可以用手工丑陋的方式做到这一点,但希望有人知道更有效的方法来填充数组。
谢谢。
答案 0 :(得分:1)
你走了。
class Alphabet {
public static void main(String args[]) {
// Create an array that will hold the grid
char alphGrid[][] = genArray();
// Two for loops to print the grid on the screen
for(int i=0; i<26; i++) {
for(int j=0; j<26; j++) {
System.out.print(alphGrid[i][j]);
}
System.out.println();
}
} // end of main
// Create a function to generate the grid
public static char[][] genArray(){
char[][] arr = new char[26][26];
// Two for loops to generate the grid
for(int i = 0; i < 26; i++) {
for(int j = 0; j < 26; j++) {
// Creates an int that will later be cast to a char
int let = i + j;
// Keeps the int from getting too big
if(let >= 26)
let = let - 26;
// Add 65 to the int so that the char will return letters and not ASCII symbols
let = let + 65;
// Cast the int to a char
char letter = (char)let;
// Put the char into its respective place in the array
arr[i][j] = letter;
}
}
// Returns the grid
return arr;
}
}
输出:
ABCDEFGHIJKLMNOPQRSTUVWXYZ
BCDEFGHIJKLMNOPQRSTUVWXYZA
CDEFGHIJKLMNOPQRSTUVWXYZAB
DEFGHIJKLMNOPQRSTUVWXYZABC
EFGHIJKLMNOPQRSTUVWXYZABCD
FGHIJKLMNOPQRSTUVWXYZABCDE
GHIJKLMNOPQRSTUVWXYZABCDEF
HIJKLMNOPQRSTUVWXYZABCDEFG
IJKLMNOPQRSTUVWXYZABCDEFGH
JKLMNOPQRSTUVWXYZABCDEFGHI
KLMNOPQRSTUVWXYZABCDEFGHIJ
LMNOPQRSTUVWXYZABCDEFGHIJK
MNOPQRSTUVWXYZABCDEFGHIJKL
NOPQRSTUVWXYZABCDEFGHIJKLM
OPQRSTUVWXYZABCDEFGHIJKLMN
PQRSTUVWXYZABCDEFGHIJKLMNO
QRSTUVWXYZABCDEFGHIJKLMNOP
RSTUVWXYZABCDEFGHIJKLMNOPQ
STUVWXYZABCDEFGHIJKLMNOPQR
TUVWXYZABCDEFGHIJKLMNOPQRS
UVWXYZABCDEFGHIJKLMNOPQRST
VWXYZABCDEFGHIJKLMNOPQRSTU
WXYZABCDEFGHIJKLMNOPQRSTUV
XYZABCDEFGHIJKLMNOPQRSTUVW
YZABCDEFGHIJKLMNOPQRSTUVWX
ZABCDEFGHIJKLMNOPQRSTUVWXY
答案 1 :(得分:0)
我在这里有所收获!不是最好的,但也许会喜欢它。
import java.util.ArrayList;
import java.util.List;
public class Alphabet{
public static void main(String[] args){
char[] c = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
List<String> s = new ArrayList<>(9);
for(int i = 0; i < c.length; i+=3){
try{
s.add(""+c[i] + c[i + 1] + c[i + 2]);
}catch(Exception e){
try{
s.add(""+c[i] + c[i + 1]);
}catch(Exception e1){
try{
s.add(""+c[i]);
}catch(Exception e2){
}
}
}
}
System.out.println(s);
}
}
输出:[abc,def,ghi,klm,nop,qrs,tuv,wxy,z]