Home > other >  g cannot be resolved to a variable
g cannot be resolved to a variable

Time:02-02

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 ?

CodePudding user response:

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.

  • Related