Java variables not initialized error

2019-01-15 22:30发布

问题:

I am getting the following error in my Java program:

Java variables not initialized error... error : variable nam and r not initialized location class child

But nan and r already initialized, yet I am still getting the same error.

public class cla {
    int rn;
    String name;

    void get(String a, int x) {
        name = a;
        rn = x;
    }

    void display() {
        System.out.println("student name: " + name + "roll no.:" + rn);
    }
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class child {
    public static void main(String args[]) throws IOException {
        String nam;
        int r;
        BufferedReader bReader = new BufferedReader(new InputStreamReader(
            System.in));
        try {
            System.out.println("enter name and roll no.");
            nam = bReader.readLine();
            r = Integer.parseInt(bReader.readLine());

        } catch (Exception e) {
        }
        cla c = new cla();
        c.get(nam, r);
        c.display();
    }

回答1:

Local variables don't get default values, you should initialize them before you use them , initialize nam and r with default values inside your main and you will be fine.

public static void main(String args[]) throws IOException{
String nam=null;
int r=0;

BTW, consider naming your class's and variables something meaningful.



回答2:

Initialize your local variable before using it, like in above case it must be String nam = "" or it can be null also; int r = 0;

When we define any instance variables in class they are default initialized eg. int to 0 but local variable needs to be initialized before using it.

Thanks, Brijesh



回答3:

It is always good practice to give your variables a value of null or zero depending on the data type you are working with. If you look over your code there you will see that you did not tell the variables their values for example you have a variable r; instead make your integer know that there is nothing inside it before you start using it like this int r = 0;. that way your java program will know that it is overriding the existing value when you use that variable. Telling your variable what they hold is what java calls initializing. Take it in the day to day activities and see it while you are coding.