简体   繁体   English

在2D数组中打印中间的行和列

[英]Print middle row and column in 2D array

I have created a 2D array, where the user can choose its size and values. 我创建了一个2D数组,用户可以在其中选择其大小和值。 But I am having trouble trying to print its middle row and column. 但是我在尝试打印其中间的行和列时遇到了麻烦。 How do I solve this problem? 我该如何解决这个问题?

public static void main(String args[])
{
    int row, col, i, j;
    int a[][]=new int[10][10];

    do{
    Scanner sc=new Scanner (System.in);
    System.out.println("Enter the order of a square matrix :");
    row=sc.nextInt();
    col=sc.nextInt();
    /* checking order of matrix and then if true then enter the values
     * into the matrix a[][]
    */

    if(row == col)
    {
        System.out.println("Enter elements in the matrix:"+row*col);
        for(i=0; i<row; i++)
        {
            for(j=0; j<col; j++)
            a[i][j]=sc.nextInt();
        }
    }
    } while(row != col);
   // Display the entered value
    System.out.println ("You have entered the following matrix");


    for (i=0; i<row; i++)
   {
       for (j=0; j<col; j++)
       System.out.print (a[i][j] + " ");
       System.out.println ();
    }
import java.util.Scanner;

public class HelloWorld{

 public static void main(String []args){
   int row, col, i, j;
   int arr[][] = new int[10][10];
   Scanner scan = new Scanner(System.in);

   // enter row and column for array.
   System.out.print("Enter row for the array (max 10) : ");
   row = scan.nextInt();
   System.out.print("Enter column for the array (max 10) : ");
   col = scan.nextInt();

   // enter array elements.
   System.out.println("Enter " +(row*col)+ " Array Elements : ");
   for(i=0; i<row; i++)
   {
       for(j=0; j<col; j++)
       {
           arr[i][j] = scan.nextInt();
       }
   }

   // the 2D array is here.
   System.out.print("The Array is :\n");
   for(i=0; i<row; i++)
   {
       for(j=0; j<col; j++)
       {
           System.out.print(arr[i][j]+ "  ");
       }
       System.out.println();
   }
   // This prints the mid row
   if((row%2)!=0 ){
     int midNumber = (row-1)/2;
         System.out.println("Mid Row is");
         for(j=0; j<col; j++)
         {
             System.out.print(arr[midNumber][j]+ "  ");
         }
   }
   // This prints the mid column
   if((col%2)!=0){
     int midNumber = (col-1)/2;
        System.out.println("Mid Column is");
        for(j=0; j<row; j++)
        {
          System.out.print(arr[j][midNumber]+ " ");
        }
   }
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM