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



我正在学习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 ++) {

对于多维数组的循环,它必须像这样

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

你可以在这里找到关于在java中迭代多维数组。

把二维数组想象成一个表格。第一个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

相关内容

  • 没有找到相关文章