[英]Java: not able to get value
常量类:
public class Constants {
FileHandle h = new FileHandle();
String[] LIST_DATA3 = h.getA().split(Pattern.quote("."));
public static int NEW_ELEMENT_ID =0;
}
FileHandle类:
public class FileHandle {
String a;
String b;
String c;
String d;
public void openFile() throws FileNotFoundException {
File dir = new File("DB");
if (!dir.exists()){
dir.mkdirs();
}
// System.out.println(dir.getAbsolutePath());
if (dir.isDirectory()) {
for (File file : dir.listFiles()) {
try (Scanner s = new Scanner(file)) {
if (s.hasNext()) {
this.a = (a == null) ? s.next() :a + "."+s.next();
b = (b == null) ? s.next() :b + "." + s.next();
c = (c == null) ? s.next() :c + "." + s.next();
d = (d == null) ? s.next() :d + "." + s.next();
}else{
s.close();
}
}
}System.out.println(a);
}
}
public String getA(){
if(this.a !=null){
System.out.println(this.a);
}
return this.a;
}
}
错误:
Exception in thread "main" java.lang.NullPointerException
at databasesearch.Constants.<init>(Constants.java:16)
at databasesearch.Frame.CreatingGUI(Frame.java:63)
at databasesearch.DatabaseSearch.main(DatabaseSearch.java:23)
C:\Users\D1sturbance\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 1 second)
框架63线:
SwingJList<String> myJList = new SwingJList<>(Arrays.asList(con.LIST_DATA3));
我的问题(我认为,如果我错了,请告诉我):获取NPE,因为Constants假设getA()返回的是非null-它甚至没有调用openFile(),因此在这种情况下它始终为null。 我该如何解决?
在您的DatabaseSearch类中编写以下代码:
String aaaa;
public DatabaseSearch(){
FileHandle h = new FileHandle();
try {
h.openFile();
} catch (FileNotFoundException ex) {
Logger.getLogger(DatabaseSearch.class.getName()).log(Level.SEVERE, null, ex);
}
pirmas = h.a;
System.out.println(pirmas+"cia");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.