Распечатать среднюю строку и столбец в 2D массиве - PullRequest
0 голосов
/ 20 марта 2019

Я создал 2D-массив, где пользователь может выбрать его размер и значения.Но у меня возникают проблемы при попытке печати его среднего ряда и столбца.Как мне решить эту проблему?

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 ();
    }

1 Ответ

1 голос
/ 20 марта 2019
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]+ " ");
        }
   }
 }
...