简体   繁体   English

Java变量未初始化错误

[英]Java variables not initialized error

I am getting the following error in my Java program: 我的Java程序中出现以下错误:

Java variables not initialized error... error : variable nam and r not initialized location class child Java变量未初始化错误...错误:变量nam和r未初始化位置类子级

But nan and r already initialized, yet I am still getting the same error. 但是nanr已经初始化,但是我仍然遇到相同的错误。

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

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. Local variables不会获取默认值 ,使用它们之前应先对其进行初始化,使用main内部的默认值初始化namr可以了。

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

BTW, consider naming your class's and variables something meaningful. 顺便说一句,考虑为您的类和变量命名有意义。

Initialize your local variable before using it, like in above case it must be String nam = "" or it can be null also; 在使用它之前先初始化您的局部变量,就像在上面的例子中一样,它必须是String nam =“”或也可以为null。 int r = 0; 整数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. int设为0,但是局部变量需要在使用之前进行初始化。

Thanks, Brijesh 谢谢,Brijesh

It is always good practice to give your variables a value of null or zero depending on the data type you are working with. 始终要根据您使用的数据类型为变量赋予null或零值。 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; 如果查看代码,您会发现您没有告诉变量其值,例如,您有一个变量r; instead make your integer know that there is nothing inside it before you start using it like this int r = 0; 相反,在开始使用它之前,先让整数知道里面没有任何东西,例如int r = 0; . that way your java program will know that it is overriding the existing value when you use that variable. 这样,当您使用该变量时,您的Java程序就会知道它正在覆盖现有值。 Telling your variable what they hold is what java calls initializing. 告诉变量它们拥有什么是Java所谓的初始化。 Take it in the day to day activities and see it while you are coding. 参加日常活动,并在编码时查看。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM