【问题标题】:populating 2d array java with char array用char数组填充二维数组java
【发布时间】:2013-04-05 04:32:06
【问题描述】:

如何将 char 1d 数组转换为 2d 数组,然后通过一次读取每一列来打印 2d 数组。即使用参数“-encrypt abcd”

public class CHARSTRING {


public static void main(String[] args) {

    String encrypt = args[0];
    String letters = args[1];
     //length of letters to be encrypted
    int n = letters.length();
    char Rows [] = letters.toCharArray();       

    if (encrypt.equals("-encrypt")) {

        if ( (n*n)/n == n) {

            int RootN = (int) Math.sqrt(n); //find depth and width of 2d array
            char [][] box = new char [RootN][RootN]; //declare 2d array

        for (int i=0; i<RootN; i++) {
            for (int j=0; j<RootN; j++) {
                box[i] = Rows;
                System.out.println(Rows); 

//输出为4行: abcd

但我试图让输出为“acbd”

【问题讨论】:

  • 所以你希望第一行的输出是 abcd?

标签: arrays for-loop multidimensional-array char


【解决方案1】:

在最后的双循环中,一个循环用于行,一个用于列。不要使用:

    for (int i=0; i<RootN; i++) {
        for (int j=0; j<RootN; j++) {
            box[i] = Rows;
            System.out.println(Rows);
        }
    }

使用 println 打印 Rows 的每个值,因此它在每行之后添加一个“\n”。相反,请尝试使用:

    for (int i=0; i<RootN; i++) {
        for (int j=0; j<RootN; j++) {
            box[i] = Rows;
            System.out.print(Rows);
        }
        System.out.println();
    }

这样,所有值都应该打印在同一行,然后更改为新行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-17
    • 1970-01-01
    • 2016-05-27
    相关资源
    最近更新 更多