Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

g cannot be resolved to a variable

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading