Java variables not initialized error

本秂侑毒 提交于 2019-11-26 23:43:07

问题


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.



来源:https://stackoverflow.com/questions/14484550/java-variables-not-initialized-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!