簡體   English   中英

使用數組的Java矩陣

[英]Java Matrix using Arrays

我正在努力尋找以下問題的答案。 用戶輸入行和列。 下面的示例給出了4 x 4矩陣。

1 8 9 16

2 7 10 15

3 6 11 14

4 5 12 13

在打印數組時,我找不到如何關聯數字。 唯一明顯的關系是它如何向下和向上。 從我的角度來看,確實很難。 我只是一個初學者。

不太確定是否有任何需要發布代碼的地方,但這只是基本內容:

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.println("Please enter your array rows: ");
    int rows = scanner.nextInt();

    System.out.println("Please enter your array columns: ");
    int columns = scanner.nextInt();

    int[][] array = new int[rows][columns];

    int counter = 0;
    for (int j = 0; j < columns; j++){
        for (int i = 0; i < rows; i++) {
            counter++;
            array[i][j]=...(stuck at the beginning);
        }

可能我需要使用多個循環,不僅是上面提到的循環,還是可能是完全錯誤的。。。謝謝您!

我認為應該這樣做。

    int counter = 0;
    boolean top_to_bottom=true;
    for (int j = 0; j < columns; j++){
        for (int i = 0; i < rows; i++) {
            counter++;
            if(top_to_bottom)
             array[i][j]=counter;
            else
             array[rows-1-i][j]=counter;
        }
        if(top_to_bottom)
         top_to_bottom=false;
        else top_to_bottom=true;
    }

它達到目的

導入java.util。*;

公共課Seq

{

公共靜態void main(String [] args)

{

掃描儀掃描儀=新的Scanner(System.in);

System.out.println(“請輸入您的數組行:”);

int行= Scanner.nextInt();

System.out.println("Please enter your array columns: ");

int列= Scanner.nextInt();

 int[][] array = new int[rows][columns];

  int counter = 0;

for(int j = 0; j <列; j ++){

if(j%2 == 0){

 for (int i = 0; i < rows; i++)
     {
        counter=counter+1;
            array[i][j]=counter;

        }
 } 
else

 {
      for (int i = rows-1; i >=0; i--) 

          {
                counter=counter+1;

                array[i][j]=counter;

            }
     }

  }

  for(int i=0;i<rows;i++)

    {

        for(int j=0;j<columns;j++)
      {

        System.out.print(array[i][j]+" ");

        }
        System.out.println();
         }
   }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM