2014-11-25 2 views
1

Так что я знаю, что подобный вопрос задавался в отношении этой ошибки. Я знаю, это потому, что с кодом что-то не так, поэтому он не компилируется. Моя проблема в том, что я не знаю, где именно в моем коде ошибка, и я не могу понять это. Чтобы подвести итог программе, это синтаксический анализатор XML, который создает структуру данных TreeNode и экспортирует ее в excel. До того, как я добавил функцию экспорта в excel, он работал отлично. Но когда я использовал apache poi для экспорта в excel, по какой-то причине возникли проблемы с компиляцией, но я не вижу, как это может быть причиной ошибки. Может ли кто-нибудь определить, что/где в коде возникает эта проблема? CheersИсключение в теме «main» java.lang.Error: Неразрешенная компиляция

Редактировать: - извинения! Это ошибка: - Исключение в потоке «основной» java.lang.Error: Нерешенные проблемы компиляции: в HMDB.XML.main (XML.java:200)

Это странно, так как линия кодирования кажется для того, чтобы произойти, это пустая строка. По-видимому, происходит в методе Подэлементы, непосредственно ниже этого бита кода: -

'} else if (event == XMLStreamConstants.CHARACTERS 
      && !reader.isWhiteSpace()) { 

     newNode.getElement().setValue(reader.getText())' 

Это код: -

пакет HMDB;

import org.apache.poi.hssf.usermodel.HSSFWorkbook; 
import org.apache.poi.ss.usermodel.Cell; 
import org.apache.poi.ss.usermodel.Row; 
import org.apache.poi.ss.usermodel.Sheet; 
import org.apache.poi.ss.usermodel.Workbook; 

import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.FileOutputStream; 
import java.io.InputStream; 

import javax.xml.parsers.FactoryConfigurationError; 
import javax.xml.stream.XMLInputFactory; 
import javax.xml.stream.XMLStreamConstants; 
import javax.xml.stream.XMLStreamException; 
import javax.xml.stream.XMLStreamReader; 
public class XML { 

private int rowNum = 0; 
private int columnNum = 0; 

public XMLStreamReader xmlInput() { 

    XMLStreamReader reader = null; 

    try { 

     XMLInputFactory inputFactory = XMLInputFactory.newInstance(); 
     InputStream file = new FileInputStream(
       "Users/kevlar/Dropbox/PhD/Java/Metabolites/src/HMDB/HMDB00316.xml"); 
     reader = inputFactory.createXMLStreamReader(file); 

    } catch (XMLStreamException e) { 
     System.err.println("XMLStreamException : " + e.getMessage()); 

    } catch (FactoryConfigurationError e) { 
     System.err.println("FactoryConfigurationError : " + e.getMessage()); 

    } catch (FileNotFoundException e) { 
     System.err.println("FileNotFoundException : " + e.getMessage()); 

    } 
    return reader; 
} 

private void findElements(String input) throws XMLStreamException { 

    TreeNode[] children; 
    Workbook wb = new HSSFWorkbook(); 
    Sheet sheet1 = wb.createSheet("Metabolites"); 
    String[] elementsSplit = input.split("\\s*,\\s*"); 
    xmlInput(); 
    XMLStreamReader reader = xmlInput(); 
    reader.nextTag(); 

    do { 
     if (reader.getEventType() == XMLStreamConstants.START_ELEMENT 
       && reader.getLocalName() == "metabolite") { 
      children = mainElements(reader).children(); 

      printValues(children, elementsSplit, sheet1); 
      children = null; 
     } else { 
      reader.next(); 
     } 
    } while (reader.hasNext()); 

    reader.close(); 

    try { 
     FileOutputStream output = new FileOutputStream("HMDB.xls"); 
     wb.write(output); 
     output.close(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

} 

private void printValues(TreeNode[] children, String[] elementsSplit, 
     Sheet sheet1) { 

    rowNum++; 
    Row row = sheet1.createRow(rowNum); 
    Cell cell = row.createCell(columnNum); 

    for (int i = 0; i < children.length; i++) { 
     TreeNode element = children[i]; 
     String elementName = element.getElementName(); 

     for (int j = 0; j < elementsSplit.length; j++) { 
      String searchName = elementsSplit[j]; 

      if (searchName.equals(elementName)) { 

       if (element.hasChildren()) { 
        recurse(element.children(), cell); 
       } else { 
        columnNum++; 
        cell.setCellValue(element.getElementValue()); 
        System.out.println("Element:- " 
          + element.getElementName() + " | Value:- " 
          + element.getElementValue()); 
       } 
      } 
     } 
    } 

    cell = null; 
} 

private void recurse(TreeNode[] children, Cell cell) { 

    for (int i = 0; i < children.length; i++) { 
     TreeNode node = children[i]; 
     if (node.hasChildren()) { 
      System.out.println("Element:- " + node.getElementName() 
        + " and it's subelements:- "); 
      recurse(node.children(), cell); 
     } 

     else if (!node.hasChildren()) { 
      columnNum++; 
      cell.setCellValue(node.getElementValue()); 
      System.out.println("Element:- " + node.getElementName() 
        + " | Value:- " + node.getElementValue()); 
     } 
    } 
} 

private TreeNode mainElements(XMLStreamReader reader) 
     throws XMLStreamException { 

    Element rootElement = new Element(); 
    rootElement.setName(reader.getLocalName()); 
    TreeNode root = new TreeNode(rootElement); 

    int level = 1; 

    do { 
     int event = reader.next(); 

     if (event == XMLStreamConstants.START_ELEMENT) { 

      Element element = new Element(); 
      element.setName(reader.getLocalName()); 
      TreeNode node = new TreeNode(element); 
      level++; 

      if (level == 2) { 
       root.add(subElements(reader, node)); 
       level--; 

      } 

     } else if (event == XMLStreamConstants.END_ELEMENT) { 
      level--; 
     } 

    } while (level > 0); 

    return root; 
} 

private TreeNode subElements(XMLStreamReader reader, TreeNode node) 
     throws XMLStreamException { 

    int level = 1; 

    TreeNode newNode = new TreeNode(); 
    newNode = node; 

    do { 
     int event = reader.next(); 

     if (event == XMLStreamConstants.START_ELEMENT) { 

      Element subElement = new Element(); 
      subElement.setName(reader.getLocalName()); 
      TreeNode subNode = new TreeNode(subElement); 
      level++; 

      if (level == 2) { 
       newNode.add(subElements(reader, subNode)); 
       level--; 
      } 

     } else if (event == XMLStreamConstants.CHARACTERS 
       && !reader.isWhiteSpace()) { 

      newNode.getElement().setValue(reader.getText()); 

     } else if (event == XMLStreamConstants.END_ELEMENT) { 
      level--; 
     } 

    } while (level > 0); 

    return newNode; 
} 

public static void main(String[] args) throws XMLStreamException { 

    XML test = new XML(); 
    test.findElements("accession, inchikey"); 

} 

} 

package HMDB; 

public class Element { 

private String name; 
private String value; 

public void setName(String name){ 
    this.name = name; 
} 

public void setValue(String value){ 
    this.value = value; 
} 

public String getName(){ 
    return name; 
} 

public String getValue(){ 
    return value; 
} 

} 


package HMDB; 

public class TreeNode{ 


/** 
* This is the nodes parent node. If it is the root of the tree, 
* then it will be null 
*/ 
private TreeNode parent; 

/** 
* An array of all this nodes children nodes. If it's a leaf node 
* i.e. node with no children, then length will be zero 
*/ 
private TreeNode[] children = new TreeNode[0]; 

private Element element; 

public TreeNode() 
{ 

} 

/** 
* Assigns the element object of this tree node to the one passed 
* through 
* @param element 
*/ 
public TreeNode(Element element){ 
    this.element = element; 
} 

public void setElement(Element element){ 
    this.element = element; 
} 

public Element getElement(){ 
    return element; 
} 

public String getElementName(){ 
    return element.getName(); 
} 

public String getElementValue(){ 
    return element.getValue(); 
} 



/** 
    * Adds the <code>child</code> node to this container making this its parent. 
    * 
    * @param child is the node to add to the tree as a child of <code>this</code> 
    * 
    * @param index is the position within the children list to add the 
    * child. It must be between 0 (the first child) and the 
    * total number of current children (the last child). If it is 
    * negative the child will become the last child. 
    */ 
    public void add (TreeNode child, int index) 
    { 
    // Add the child to the list of children. 
    if (index < 0 || index == children.length) // then append 
    { 
     TreeNode[] newChildren = new TreeNode[ children.length + 1 ]; 
     System.arraycopy(children, 0, newChildren, 0, children.length); 
     newChildren[children.length] = child; 
     children = newChildren; 
    } 
    else if (index > children.length) 
    { 
     throw new IllegalArgumentException("Cannot add child to index " + index + ". There are only " + children.length + " children."); 
    } 
    else // insert 
    { 
     TreeNode[] newChildren = new TreeNode[ children.length + 1 ]; 
     if (index > 0) 
     { 
     System.arraycopy(children, 0, newChildren, 0, index); 
     } 
     newChildren[index] = child; 
     System.arraycopy(children, index, newChildren, index + 1, children.length - index); 
     children = newChildren; 
    } 

    // Set the parent of the child. 
    child.parent = this; 
    } 

    /** 
    * Adds the <code>child</code> node to this container making this its parent. 
    * The child is appended to the list of children as the last child. 
    */ 
    public void add (TreeNode child) 
    { 
    add(child, -1); 
    } 

    /** 
    * Gets a list of all the child nodes of this node. 
    * 
    * @return An array of all the child nodes. The array will 
    * be the size of the number of children. A leaf node 
    * will return an empty array, not <code>null</code>. 
    */ 
    public TreeNode[] children() 
    { 
    return children; 
    } 

    /** 
    * Returns if this node has children or if it is a leaf 
    * node. 
    * 
    * @return <code>true</code> if this node has children; <code>false</code> 
    * if it does not have any children. 
    */ 
    public boolean hasChildren() 
    { 
    if (children.length == 0) 
    { 
     return false; 
    } 
    else 
    { 
     return true; 
    } 
    } 

    /** 
    * Gets the position of this node in the list of siblings 
    * managed by the parent node. This node can be obtained 
    * by <code>this = parent.children[this.index()]</code>. 
    * 
    * @return The index of the child array of this node's 
    * parent. If this is the root node it will return -1. 
    */ 
    public int index() 
    { 
    if (parent != null) 
    { 
     for (int i = 0; ; i++) 
     { 
     Object node = parent.children[i]; 

     if (this == node) 
     { 
      return i; 
     } 
     } 
    } 

    // Only ever make it here if this is the root node. 
    return -1; 
    } 

} 
+2

Вы всегда должны публиковать сообщение об ошибке ... – Kon

+0

Полная трассировка стека, если это возможно, и отметьте линию, когда это произойдет в вашем коде. Если это действительно ошибка компиляции, а не исключение, возникшее при запуске программы, скопируйте текст ошибки точно (и по-прежнему отметьте строку в коде, где она происходит). – RealSkeptic

+0

Просто обновил вопрос, указав, где это происходит с сообщением об ошибке, извините! – user2062207

ответ

1

Это еще не все импорт. Вам не хватает импорта для объектов TreeNode и Element. Вам нужно импортировать эти классы, чтобы использовать их в вашем файле. Это единственные ошибки компиляции на основе кода, который вы опубликовали.

+0

Просто добавили их сейчас! – user2062207

+0

@ user2062207 Нет, у вас нет. – Kon

+0

Я отредактировал раздел кода в сообщении выше с классами TreeNode и Element под XML. Класс TreeNode и Element являются частью одного и того же пакета, поэтому я просто создаю классы для создания объектов из них. – user2062207

Смежные вопросы