#java #arrays #println
#java #массивы #println
Вопрос:
Я создал 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. Я запустил ваш код и не вижу в нем никаких очевидных ошибок, какой результат вы ожидаете?
2. В чем проблема?
3. пытаюсь напечатать среднюю строку по отдельности, а также средний столбец
4. Для размера 3×3 вам нужно значение в ячейке (2,2)? какое значение ячейки вам нужно для 2×2?
5. я хочу напечатать всю среднюю строку
Ответ №1:
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] " ");
}
}
}