如何使用二维数组编写for循环

时间:2014-07-25 04:21:00

标签: arrays multidimensional-array

我只是在学习java,在完成作业时遇到了问题。我需要使用for循环,但我不确定正确的编码。我能够编译我的代码以获得第一次挑战的输出,但我无法为剩余的挑战这样做。任何建议/提示非常感谢。

/Your instructor is in a bind.  His place of work has instituted a new 
//technology project that will require remote access verification. 
//In addition to his user name and password, he will have a “challenge” 
//to each sign-on. That challenge will require that he input a number or 
//letter depending on what the security application asks him.
//But your instructor is lazy. He wants an application that will 
//tell him what those appropriate numbers are without him having to 
//look them up each time.  He understands that this will help foil 
//remote hackers, but he does not want to be stuck carrying around a piece of paper all the time.

//Write your instructor a program that gives him the three characters asked for.  The matrix to use is:
//A B C D E F G H I J 
//1 3 N 1 M 4 R X 5 F N
//2 N V T 5 K Q F M 3 P
//3 9 K 1 Y R 4 V T F 3
//4 3 3 9 V 4 Y R T N N
//5 3 1 1 3 2 9 X P N P

//A challenge of A1:B2:C3 would yield 3 V 1.
//A challenge of G4:D2:J3 would yield R 5 3.

// 1. Create a place to accept input
            //  ---- create a scanner class
            // 2. ask for input  
            String  input = "a1";


            // 3. Take the first character from the challenge
            //      (like "D2" would "D" and find its analogous int array value)

            int i1 = Util.findFirstValue(input);
            System.out.println(i1);

            // 4.Take the second character from the challenge (like "D2"
            //      would be "2") and find its analogous int array value
            //      Hint: always one less than the value entered.
            int i2 = Util.findSecondValue(input);
            System.out.println(i2);

            // 5. inquire with the array with the challenge values to get the desired value

            System.out.println(Util.findArrayValue(i1, i2));

            // 6. display the value 
            // 7. repeat twice more steps 2 through 6
        }


        {   
        for (int row =1; row<9;row ++) {
        for (int column =2; column <5;column ++) {

2 个答案:

答案 0 :(得分:0)

对于循环多维数组,它必须喜欢这个

for(int i=0; i<multiarray[i].length; i++) {
multiarray[i][k]; //do something with it!
}

您可以在java中找到关于迭代多维数组的heree

答案 1 :(得分:0)

想象一个像桌子一样的2D数组。从该表中获取的第一个for循环,然后下一个for循环从该行获取某个元素()。

1, 2, 3
4, 5, 6     -->        4, 5, 6       -->         6
7, 8, 9   array[1]               array[1][2]    

所以基本上。第一个循环获取2D数组中的基本数组,下一个获取该基本数组中的精确值。

<强> 代码:

int[][] A = { {1,2,3},
              {4,5,6},
              {7,8,9} };

for(int i = 0; A.length>i; i++) {
    for(int j = 0; A[0].length>j; j++) {
        System.out.println(A[i][j]);
    }
}

<强> 输出:

1
2
3
4
5
6
7
8
9