得到一个字符串变量中有2级2 main
:如何从另一个类
- 类
New_String
用于从我的文件中读取文本文件。 - 类别
Write
用于显示New_String
类的读取值S1(=ar[1])
。
但是,无论我怎样努力,在Write
类是只显示null
,或者抛出一个NullPointerException
错误。
因为程序在我的下一个阶段有进一步的功能,所以我不能只将2个类合并为一个。请告诉我如何调整。
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];
}
}
每个主()在其自己的JVM实例运行作为因此,基本上你有2个进程正在运行..不是同一进程的2个线程。因此,2个进程不能在没有IPC的情况下共享数据。 – TheLostMind
那么,你正在使用写入类中的主函数来启动应用程序。所以New_string类中的主函数永远不会被调用,因此New_string.S1字段为null。在两个不同类中有两个主要方法的事实并不意味着当你启动程序时,每个程序都会被调用,而不是其中的一个。在写入内部的主要方法应该首先调用New_string.main(null),然后期望在New_string.S1 –