正确的格式

时间:2013-12-04 19:34:48

标签: java for-loop formatting

我被告知此代码中的格式已关闭,有人可以告诉我它有什么问题吗?

public class TwoDimArray {
    public static void main(String[] args) {
        int rows = 2;
        Int columns = 2;
        String[][] anArray = {{"Ireland", "Green"},{"England", "White"}};

        for (int i = 0; i < rows; i++){
            for (int j = 0; j < columns; j++){
                System.out.println(anArray[i][j]);
            }
        }
    }
}

此外,任何人都可以告诉我如何打印它:

Ireland Green

England White

As apposed to:

Ireland

Green

England

White

2 个答案:

答案 0 :(得分:0)

您编写的代码有错误:

Int columns = 2; 

这将是正确的代码:

int columns = 2;

如果您希望代码具有此输出:

爱尔兰绿色

英格兰怀特

您可以使用此代码:

public class TwoDimArray {
public static void main(String[] args) {

    String[][] anArray = {{"Ireland", "Green"},{"England", "White"}};

    for (int i = 0; i < anArray.length; i++){
        for (int j = 0; j < anArray.length; j++){
            System.out.print(anArray[i][j] + " ");
        }
        System.out.println();
    }

    }
}

我希望了解并帮助你

幸运的是

答案 1 :(得分:0)

    public class TwoDimArray {
public static void main(String[] args) {

    String[][] anArray = {{"Ireland", "Green"},{"England", "White"}};   // create your array 2 dimensions

    for (int i = 0; i < anArray.length; i++){     // create for, .length is the array size, 
        for (int j = 0; j < anArray.length; j++){
            System.out.print(anArray[i][j] + " ");    // print the element of array and add one space for print with you want
        }
        System.out.println();    //when end the FOR with J variable, you has printed the row, and with println, add a one new line
    }

    }
}

.length 你得到一个可变的大小/长度,在这种情况下你的数组是 array [2] [2]

我使用 println 因为当结束 println 时,此方法在结束行中引入一个新行,一行跳转,然后是下一个 println 写入将在新行中。

然而打印,与 print 相同,在C语言中,只有写入,而下一个 print 将首先在 >打印 ...所以我在末尾打印

输入+“”
for (int i = 0; i < anArray.length; i++){
    for (int j = 0; j < anArray.length; j++){
        System.out.print(anArray[i][j] + " ");// First iteration of the FOR :Ireland" " second iteration of the FOR : Green" "
    }
    System.out.println(); // add a line jump for the next FOR iteration...
}
    } 

如果您仍然不明白,可以尝试更改de“”for“,”或者您可以尝试更改println进行打印,您将开始理解

我希望现在帮助你jajaja

祝你好运