[英]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.