Adrian2895:
私は、javaの行によって多次元の行にアクセスしようとしていますが、私はそれを達成することができません。
私はこのコードを持っているが、それは、列によって配列の列を出力します:
for(int i = 0; i<array.length; i++) {
for(int j = 0; j<array[i].length; j++) {
System.out.print(array[i][j]);
}
}
だから、例えば私は、この配列を持っている場合:
[["a", "b", "c"], ["d", "e", "f"], ["g", "h", "i"]]
どのように私はこの方法でそれをプリントアウトすることができますか?
adg
beh
cfi
完全なコード:
import java.util.Scanner;
public class forcabruta {
public static void main (String[] args) {
Scanner keyboard = new Scanner(System.in);
char[] words = new char[] {'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', ' '};
String text;
System.out.print("Enter a text to decode: ");
text = keyboard.nextLine();
char[][] combinations = new char[text.length()][words.length];
for(int i = 0; i<text.length(); i++) {
for(int j = 0; j<words.length; j++) {
if(words[j] == text.charAt(i)) {
for(int k = 1; k<words.length; k++) {
combinations[i][k] = words[Math.floorMod(j-k, 27)];
}
}
}
}
for(int i = 0; i<combinations.length; i++) {
for(int j = 0; j<combinations[i].length; j++) {
System.out.print(combinations[j][i]);
}
}
}
}
Hermueller:
インデックスを切り替えるのは注意してください!
たとえば、これはエラーをスローしていました。
String[][] array = {{"a", "b", "c"}, {"d", "e", "f"}, {"g", "h", "i"}, {"j", "k"}};
for(int i = 0; i<array.length; i++) {
for(int j = 0; j<array[i].length; j++) {
System.out.print(array[j][i]);
}
System.out.println();
}
ベターはこれです:
String[][] array = {{"a", "b", "c"}, {"d", "e", "f"}, {"g", "h", "i"}, {"j", "k"}};
int maxColCount = 0;
int i = -1;
do {
i++;
for(int j = 0; j < array.length; j++) {
if (array[j].length > i) {
System.out.print(array[j][i]);
}
if (array[j].length > maxColCount) {
maxColCount = array[j].length;
}
}
System.out.println();
} while (i < maxColCount);
基本的な考え方は、あなたが持っているどのように多くの列がわからない、あなたが仕事をしながら自分でそれを見つけなければならないということです。しかし、あなたはまた、現在の行がそれにアクセスする前に、非常に多くの列を持っているかどうかを毎回確認する必要があります。
列の量が常に同じであれば、これで十分です。
String[][] array = {{"a", "b", "c"}, {"d", "e", "f"}, {"g", "h", "i"}};
for(int i = 0; i < array[0].length; i++) {
for(int j = 0; j < array.length; j++) {
System.out.print(array[j][i]);
}
System.out.println();
}