Java 变量未初始化错误 [英] Java variables not initialized error

查看:28
本文介绍了Java 变量未初始化错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 Java 程序出现以下错误:

I am getting the following error in my Java program:

Java 变量未初始化错误...错误:变量 nam 和 r not初始化位置类子

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

但是 nanr 已经初始化,但我仍然遇到同样的错误.

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

推荐答案

局部变量没有获得默认值,使用前应该先初始化,初始化namr 在你的 main 中使用默认值,你会没事的.

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.

这篇关于Java 变量未初始化错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆