2015-10-15 155 views
-3

我正试图编写一个程序,它将条目放入列表中。然而,当我测试从文件中读取输入的功能,我得到一个错误,说明Java:非静态类和静态调用

Cannot make a static reference to the non-static field aBook 

当我让静态然而,该方案只是打印出空白项。

下面是相关作品 本公司主营:

import java.io.*; 
import java.util.*; 

public class AddressBookApplication { 
    AddressBook aBook = new AddressBook(null, null, null, null, null, null, null, null); 

    public static void main(String[] args) { 
    AddressBookApplication start = new AddressBookApplication(); 

    Scanner input = new Scanner(System.in); 
    Menu mainM = new Menu(); 
    String filename = " "; 

    mainM.mainMenu();       //Prints out a basic menu with options for input. 
    System.out.println("t) Read Test"); 
    String testChar = "";  //Activate test 
    testChar = input.next(); 
    if(testNumber.equals("t")){ 
     filename = "testfile.txt"; 
     start.init(filename); 
     System.out.println(aBook); 

    } 

则程序进入到初始化读取文件:

public void init(String f){ 
    AddressEntry newEntry = new AddressEntry(); 
    File file = new File(f); 
    try { 
     FileReader fi = new FileReader(file); 
     BufferedReader buffR = new BufferedReader(fi); 
     String lineRead; 
     while((lineRead = buffR.readLine()) != null){ 
      lineRead = buffR.readLine(); 
      newEntry.setFNAME(lineRead); 
      lineRead = buffR.readLine(); 
      newEntry.setLNAME(lineRead); 
      lineRead = buffR.readLine(); 
      newEntry.setStreet(lineRead); 
      lineRead = buffR.readLine(); 
      newEntry.setCity(lineRead); 
      lineRead = buffR.readLine(); 
      newEntry.setState(lineRead); 
      lineRead = buffR.readLine(); 
      newEntry.setZip(lineRead); 
      lineRead = buffR.readLine(); 
      newEntry.setPhone(lineRead); 
      lineRead = buffR.readLine(); 
      newEntry.setEMAIL(lineRead); 
      aBook.addEntry(newEntry); 
     } 
     buffR.close(); 
    } catch (FileNotFoundException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (IOException e){ 
     e.printStackTrace(); 
    } 
} 

AddressBook类:

import java.util.*; 

public class AddressBook extends AddressEntry { 

public AddressBook(String fn, String ln, String st, String ci, String sta, String zi, String tp, String em){ 
    super();} 

List<AddressEntry> bookA = new LinkedList<AddressEntry>(); 
public void addEntry(AddressEntry a){ 
    bookA.add(a); 
    } 
` 

如果你需要AddressEntry类,我也可以发布,但我很确定这个问题我已经从我的主要()。

+0

Java:非静态类和静态调用,编译时异常本身说明了一切。你正在做错误的访问类型。其他人已经指出你需要怎么处理你的问题 – Acewin

回答

-1

如果你要引用aBook,你需要做的静态变量:

public static AddressBook aBook 
+0

问题是,当我这样做时,程序只是打印一个空白条目。 – rreeve0102

+1

@ rreeve0102,这是一个完全不同的问题。 – BlackHatSamurai

-1

由于主()是静态的,这条线是最有可能导致此问题:

System.out.println(aBook); 

由于您在主叫中创建了一个AddressBookApplication的实例,因此“start”开始有一个对aBook的引用,因此您可以拨打:

System.out.println(start.aBook);