W
W
WWH2018-07-24 17:46:33
Java
WWH, 2018-07-24 17:46:33

How to write a program to find the row index of a matrix with the maximum sum of elements?

Why does the compiler throw an error:

Task8.java:35: error: cannot find symbol
        matrix[n][m] = scan.nextInt();
        ^
  symbol:   variable matrix
  location: class Task8
Task8.java:38: error: cannot find symbol
    System.out.println(maxSumRowIndex(matrix));
                                      ^
  symbol:   variable matrix
  location: class Task8
2 errors

For this code?
1 import java.util.Scanner;
  2 public class Task8
  3 {
  4     public static int maxSumRowIndex(int[][] arr){
  5             int max = 0;
  6             int n = 0;
  7         for(int i = 0; i < arr.length; i++){
  8             for(int j = 0; j < arr[0].length; j++){ 
  9                 if(arr[i][j] > max){
 10                     max = arr[i][j];
 11                     n = i; 
 12                 }   
 13             }   
 14         }
 15         return n;
 16     }
 17 
 18     public static void main(String[] args){
 19 
 20         int n = 0, m = 0;   
 21 
 22         Scanner scan = new Scanner(System.in);
 23 
 24         n = scan.nextInt();
 25         m = scan.nextInt();
 26 
 27         try{
 28             int[][] matrix = new int[n][m];
 29         }catch(IllegalArgumentException e){
 30             System.err.println("Ошибка" + e);
 31         }
 32 
 33         for(int i = 0; i < n; i++){
 34             for(int j = 0; j < m; j++){
 35                 matrix[n][m] = scan.nextInt();
 36             }
 37         }
 38         System.out.println(maxSumRowIndex(matrix));
 39     }
 40 }
~

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Gornostaev, 2018-07-24
@WWH

Because blocks limit the scope. Declared a variable inside a try block - you can use it only inside this block.

M
Marat Tagirov, 2018-07-30
@martagir

The variable matrix is ​​only visible inside the try block where it is declared. You either need to declare it outside the block in order to have access to it, or then put all the access code in the same try block as well

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question