g cannot be resolved to a variable

Advertisements

g cannot be resolved to a variable is the error popping up. I’ve initialised g in the for loop, so why this error ? I’m a beginner, so can anybody explain in as many simple and understandable words as possible.

import java.util.Scanner;

public class Bellman {
public static void main(String[] args) {
    
    Scanner sc = new Scanner(System.in);
    
    System.out.println("Enter the number of nodes");
    int n = sc.nextInt();
    
    System.out.println("Enter the cost matrix");
    
    for (int j = 0; j<n; j++) {
        for (int k = 0; k<n; k++) {
            int g[j][j] = sc.nextInt();
        }
    }
    
    

}
}

g cannot be resolved to a variable. I’ve initialised g in the for loop, so why this error ?

>Solution :

this is most likely what you want to achieve:

        int g[][] = new int[n][n];

        for (int j = 0; j < n; j++) {
            for (int k = 0; k < n; k++) {
                g[j][k] = sc.nextInt();
            }
        }

You have to initialize the array with a specific size, only then you can assign values at a given indexes.

Leave a ReplyCancel reply