【发布时间】:2014-03-29 04:42:43
【问题描述】:
2类中有2个main:
-
New_String类用于从我的文件中读取文本文件。 -
Write类用于显示来自New_String类的读取值S1(=ar[1])。
但是,无论我怎么尝试,Write 类都只显示null,或者它抛出一个NullPointerException 错误。
因为程序在我的下一个阶段还有更多的功能,我不能把这两个类合二为一。请告诉我如何调整。
write
public class write
{
//public static String getar=get.ar[1];
//getar = get.ar[];
public static void main(String args[]) throws IOException
{
New_string file = new New_string();
//site.readline
System.out.println(file.S1);
//String S1 = ar[1];
}
}
New_string
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
public class New_string
{
public static String S1;
public static int a=0;
public static String ar[];
public static int lnum=0;
public static String line=null;
public static void main(String args[]) throws IOException
{
FileReader fr= new FileReader("read_listflow.txt");
BufferedReader br=new BufferedReader(fr);
while ((line=br.readLine())!=null)
{
lnum=lnum+1;
}
FileReader fr1= new FileReader("read_listflow.txt");
BufferedReader br1=new BufferedReader(fr1);
ar=new String[lnum];
while ((line=br1.readLine())!=null)
{
ar[a]=line;
a=a+1;
}
S1 = ar[1];
}
}
【问题讨论】:
-
每个 main() 作为单独的进程在其自己的 JVM 实例中运行。所以,基本上你现在有 2 个进程在运行。不是同一个进程的 2 个线程。所以,2 个进程可以t 在没有 IPC 的情况下共享数据。
-
好吧,您很可能正在使用 write 类中的主函数启动您的应用程序。因此 New_string 类中的主函数永远不会被调用,因此 New_string.S1 字段为空。您在两个不同的类中有两个主要方法这一事实并不意味着当您启动程序时会调用其中的每个方法,而不是其中一个。您在 write 中的 main 方法应该首先调用 New_string.main(null),然后才能期望在 New_string.S1 中获得非空值