简体   繁体   中英

Java: not able to get value

Constants class:

public class Constants { 
    FileHandle h = new FileHandle();
    String[] LIST_DATA3 = h.getA().split(Pattern.quote("."));
    public static  int NEW_ELEMENT_ID =0;
}

FileHandle class:

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;
}
}

Error:

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)

Frame 63 line :

    SwingJList<String> myJList = new SwingJList<>(Arrays.asList(con.LIST_DATA3));

My problem (in my opinion, tell me if i am wrong): getting NPE because Constants is assuming getA() returns non-null - it's not even calling openFile(), so it's always going to be null in this case. How can i fix it ?

In your DatabaseSearch class write this:

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");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM