java - 如何逐行访问多维?
问题描述
我试图在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]);
}
}
}
}
解决方案
你几乎做到了。只需更换:
System.out.print(array[i][j]);
对此:
System.out.print(array[j][i]);
UPD 1:
所以你的代码变成:
String[][] array = {{"a", "b", "c"}, {"d", "e", "f"}, {"g", "h", "i"}};
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();
}
推荐阅读
- google-apps-script - 为什么谷歌电子表格脚本无法排序?
- python-3.x - 如何将 IBM Cloudant 数据库连接到本地 python 代码?
- c# - excel互操作字符串数组到范围,不显示为公式
- r - 从与另一个数据帧匹配的非常大的数据帧中删除行的最快方法
- ruby-on-rails - (角度 8)在 $http Post 数据中发送文件数据会在 Rails API 日志中给出 {}
- java - Itext7定位异常
- c - 为什么 brk(void *end_data_segment) 的参数不向上舍入到下一页边界?
- jsf - 在 Java PrimeFaces Extension 中恢复动态表单数据
- laravel - Laravel RESTful 和多子域
- c++ - 在特定的 Unicode 路径中创建文件