【发布时间】:2014-03-19 19:45:46
【问题描述】:
基本上我在一个程序中创建一个自定义对象并在一个程序中使用值进行实例化,然后我创建另一个程序并希望打印实例化的对象输出。
import java.util.Scanner;
class example {
int value;
String name;
String city;
}
public class Yummy21 {
static example[] obj=new example[3];
static Scanner input=new Scanner(System.in);
public static void main(String args[])
{
init();
}
public static void init()
{
for(int i=0;i<3;i++)
{
obj[i]=new example();
}
for(int i=0;i<3;i++)
{
System.out.println("for the object "+i+" enter the name ");
obj[i].name=input.next();
System.out.println("for the object "+i+" enter the city ");
obj[i].city=input.next();
System.out.println("for the object "+i+" enter the name ");
obj[i].value=input.nextInt();
}
}
}
还有下一个节目:
public class Yummy22 extends Yummy21 {
public static void main(String args[])
{
for(int j=0;j<3;j++)
{
System.out.println("the value of the object["+j+"].name is "+obj[j].name);
}
}
}
第一个程序工作正常,这意味着它接受值,第二个程序显示NullPointerException。
【问题讨论】:
-
您打算如何在这两个程序之间传递数据?
-
您是否认为
obj为空?为什么?因为你从来没有初始化它。你的代码以什么方式构成两个程序? -
当你运行 Yummy21 时,数据被创建,然后在程序结束时被丢弃。该程序与 Yummy22 的执行无关。如果您需要保留 Yummy21 生成的数据,那么您需要按照 Tyson Moncrief 的建议将其保存到某种长期存储中,例如文件。
-
感谢@dorr,我想这是唯一的解决方案!!!
标签: java class inheritance argument-passing