Java variables not initialized error

2019-01-15 22:42发布

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();
    }

3条回答
可以哭但决不认输i
2楼-- · 2019-01-15 23:17

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.

查看更多
再贱就再见
3楼-- · 2019-01-15 23:22

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

查看更多
走好不送
4楼-- · 2019-01-15 23:23

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.

查看更多
登录 后发表回答