循环不给我想要的矩阵输出

时间:2017-03-16 17:59:54

标签: java loops matrix

我试图在方形矩阵中显示一个数字数组,在蛇形图案中增加1。无法获得正确的输出。显示用户输入行/列和矩阵。看下面的照片。我还尝试使用模数的偶数/奇数行的语句,但仍然得到相同的输出。 (请耐心等待,我是新手,抱歉格式或者我缺少信息)

http://imgur.com/a/ZDhFw

import java.util.Scanner;



public class A3_Q2 {

public static void main(String[] args) 
{
    // TODO Auto-generated method stub

    Scanner keyboard = new Scanner(System.in);

    System.out.println("[-------------------------]");
    System.out.println("[      Array Pattern      ]");
    System.out.println("[-------------------------]");

    System.out.println("How many rows/columns do you want your array to have? (Mist be at least 3):");


    int arraySize = keyboard.nextInt();

    while(arraySize < 3) 
    {
        System.out.println("Lets try this again ....");
        System.out.println("How many rows/columns do you want your array to have? (Mist be at least 3):");
        arraySize = keyboard.nextInt(); 
    }


    int [][] pattern = new int[arraySize][arraySize];

    int i = 0;
    int number = 1;

    while (i < arraySize) 
    {   
        for (int j = 0; j < arraySize; ++j)
        {
            pattern[i][j] = number;
            System.out.printf("%3d", pattern[i][j]);
            number++;   
        }   

        System.out.println("");
        ++i;
        for (int j = arraySize-1; j >= 0; --j)

        {
        pattern[i][j] = number;
        System.out.printf("%3d", pattern[i][j]);
        number++;   
        }

        System.out.println("");
        ++i;    
    }   
    }   
}

2 个答案:

答案 0 :(得分:0)

我已经更改了您的代码,以便它可以运行。正如您已经提到的,您可以在此使用模运算符。

PermissionAwareActivity

答案 1 :(得分:0)

编辑:在IDE中对此进行测试以确保其有效。

首先需要为pattern [i] [j]设置初始值。

for (int i = 0; i < arraySize; i++) {
    for (int j = 0; j < arraySize; j++) {
        pattern[i][j] = arraySize*i + j + 1;
    }
}

然后你需要有一个条件,当我是偶数时会以升序打印出数字,当我是奇数时,它会下降。

for (int i = 0; i < arraySize; i++) {
    if (i % 2 == 0) {
       for (int j = 0; j < arraySize; j++) {
           System.out.printf("%3d", pattern[i][j]);
       }
    } else {
       for (int j = arraySize - 1; j >= 0; j--) {
           System.out.printf("%3d", pattern[i][j]);
       }
    }
    System.out.println();
}