Java Vector Field (private member) accumulator doesn't store my Cows!
Edit: This code is fine. I found a logic bug somewhere that doesn't exist in my pseudo code. I was blaming it on my lack of Java experience.
In the pseudo code below, I'm trying to parse the XML shown. A silly example maybe but my code was too large/specific for anyone to get any real value out of seeing it and learning from answers posted. So, this is more entertaining and hopefully others can learn from the answer as well as me.
I'm new to Java but an experienced C++ programmer which makes me believe my problem lies in my understanding of the Java language.
Problem: When the parser finishes, my Vector is full of uninitialized Cows. I create the Vector of Cows with a default capacity (which shouldn't effect it's "size" if it's anything like C++ STL Vector). When I print the contents of the Cow Vector out after the parse, it gives the right size of Vector but all the values appear never to have been set.
Info: I have successfully done this with other parsers that don't have Vector fields but in this case, I'd like to use a Vector to accumulate Cow properties.
MoreInfo: I can't use generics (Vector< Cow >) so please don't point me there. :)
Thanks in advance.
<pluralcow>
<cow>
<color>black</color>
<age>1</age>
</cow>
<cow>
<color>brown</color>
<age>2</age>
</cow>
<cow>
<color>blue</color>
<age>3</age>
</cow>
</pluralcow>
public class Handler extends DefaultHandler{
// vector to store all the cow knowledge
private Vector m_CowVec;
// temp variable to store cow knowledge until
// we're ready to add it to the vector
private Cow m_WorkingCow;
// flags to indicate when to look at char data
private boolean m_bColor;
private boolean m_bAge;
public void startElement(...tag...)
{
if(tag == pluralcow){ // rule: there is only 1 pluralcow tag in the doc
// I happen to magically know how many cows there are here.
m_CowVec = new Vector(numcows);
}else if(tag == cow ){ // rule: multiple cow tags exist
m_WorkingCow = new Cow();
}else if(tag == color){ // rule: single color within cow
m_bColor = true;
}else if(tag == age){ // rule: single age within cow
m_bAge = true;
}
}
public void characters(...chars...)
{
if(m_bColor){
m_WorkingCow.setColor(chars);
}else if(m_bAge){
m_WorkingCow.setAge(chars);
}
}
public void endElement(...tag...)
{
if(tag == pluralcow){
// that's all the cows
}else if(tag == cow ){
m_CowVec.addElement(m_WorkingCow);
}else if(tag == color){
m_bColor = false;
}else if(tag == age){
m_bAge = false;
}
}
}
Asked by: First Name736 | Posted: 21-01-2022
Answer 1
When you say that the Cows are uninitialized, are the String properties initialized to null? Or empty Strings?
I know you mentioned that this is pseudo-code, but I just wanted to point out a few potential problems:
public void startElement(...tag...)
{
if(tag == pluralcow){ // rule: there is only 1 pluralcow tag in the doc
// I happen to magically know how many cows there are here.
m_CowVec = new Vector(numcows);
}else if(tag == cow ){ // rule: multiple cow tags exist
m_WorkingCow = new Cow();
}else if(tag == color){ // rule: single color within cow
m_bColor = true;
}else if(tag == age){ // rule: single age within cow
m_bAge = true;
}
}
You really should be using tag.equals(...) instead of tag == ... here.
public void characters(...chars...)
{
if(m_bColor){
m_WorkingCow.setColor(chars);
}else if(m_bAge){
m_WorkingCow.setAge(chars);
}
}
I'm assuming you're aware of this, but this methods is actually called with a character buffer with start and end indexes.
Note also that characters(...) can be called multiple times for a single text block, returning small chunks in each call: http://java.sun.com/j2se/1.4.2/docs/api/org/xml/sax/ContentHandler.html#characters(char[],%20int,%20int)
"...SAX parsers may return all contiguous character data in a single chunk, or they may split it into several chunks..."
I doubt you'll run into that problem in the simple example you provided, but you also mentioned that this is a simplified version of a more complex problem. If in your original problem, your XML consists of large text blocks, this is something to consider.
Finally, as others have mentioned, if you could, it's a good idea to consider an XML marshalling library (e.g., JAXB, Castor, JIBX, XMLBeans, XStream to name a few).
Answered by: Caroline515 | Posted: 22-02-2022Answer 2
The code looks fine to me. I say set breakpoints at the start of each function and watch it in the debugger or add some print statements. My gut tells me that either characters()
is not being called or setColor()
and setAge()
don't work correctly, but that's just a guess.
Answer 3
I have to say that I'm not a big fan of this design. However, are you sure that your characters is ever called ? (maybe a few system.outs would help). If it's never called, you would end up with an uninitialized cow.
Also, I would not try to implement an XML parser myself like this since you need to be more robust against validation issues.
You can use SAX or DOM4J, or even better, use Apache digester.
Answered by: Rafael548 | Posted: 22-02-2022Answer 4
Also, if I have a schema I will use JaxB, or another code generator to speed up development of XML interface code. The code generators hide a lot of the complexity of working directly with SAX or DOM4J.
Answered by: Catherine322 | Posted: 22-02-2022Similar questions
Accumulator Generator test - Java 8
Paul Graham, in his great article Revenge of the Nerds, claimed that languages vary in power. He mentioned a nice exercise - writing an accumulator generator:
We want to write a function that generates accumulators-- a function
that takes a number n, and returns a function that takes another
number i and returns n incremented by i.
java - How to display current accumulator value updated in DStream?
I am processing a java jar. The accumulator adds up the stream values. The problem is, I want to display the value in my UI every time it increments or in a specific periodic interval.
But, Since the accumulators value can only be got from the Driver program, I am not able to access this value until the process finishes its execution. any idea on how i can access this value periodically?
My code is as given...
Java 8 stream parallel reduce BiFunction accumulator
I am learning Java 8. The most difficult thing I have to face is the Parallel Reduction. Here is the code from a example of the user @Stuart Marks I am studying with.
class ImmutableAverager
{
private final int total;
private final int count;
public ImmutableAverager(){this.total = 0;this.count = 0;}
public ImmutableAverager(int total, int count)
{
this.total = total;
this.coun...
java - Code keeps setting accumulator to 0?
So I am making a hangman game. I am trying, at the moment, to make an accumulator for how many wrong guesses the user gives (after 6 wrong guesses, they lose); However, my strikeCounter keeps getting set to 0 and I don't know why (thus printing out that there is always 1 strike no matter how many wrong guesses the user gives). Can someone help me see where my error is? Thank you!
//imports:
import java.util...
java - Money accumulator buttons
Closed. This question needs details or clarity. It ...
dictionary - java 8 reduce accumulator return type
I need to do a simple traversal over a list of elements, perform some kind of transformation over all of them, and them accumulate all the results in a list.
Something like this:
List<GraphEdge> edges = new LinkedList<GraphEdge>();
for (CrawlResult result : crawlResults) {
edges.addAll(resultToEdges(result));
}
This code takes 4 lines, and nothing would make me happier than...
java - About collect (supplier, accumulator, combiner)
This question already has an answer here:
java - Why does my Pig Accumulator UDF not run in accumulator mode?
I wrote an Accumulator UDF using Java. When I run the UDF on unsorted data, Pig (0.13.0) calls the accumulate method as desired:
output = FOREACH (GROUP input BY f) {
GENERATE MyUDF(input);
}
I can tell that it's working because the log declares that the reducer is running in accumulative mode.
However, when I apply a secondary sort, Pig calls the exec...
java - In the Circle Hough Transform, what is the Inverse Ratio of Accumulator Resolution (dp) and how does it affect circle detection?
The OpenCV documentation states:
dp: Inverse ratio of the accumulator resolution to the image resolution. For example, if dp=1 , the accumulator has the same resolution as the input image. If dp=2 , the accumulator has half as big width and height.
But it gives no indication how the size of this value affects circle detection. I thought the accumulator was just a collection of m...
java - Spark Accumulator value not read by task
I am initializing an accumulator
final Accumulator<Integer> accum = sc.accumulator(0);
And then while in map function , I'm trying to increment the accumulator , then using the accumulator value in setting a variable.
JavaRDD<UserSetGet> UserProfileRDD1 = temp.map(new Function<String, UserSetGet>() {
@Override
public UserSetGet call(St...
Still can't find your answer? Check out these amazing Java communities for help...
Java Reddit Community | Java Help Reddit Community | Dev.to Java Community | Java Discord | Java Programmers (Facebook) | Java developers (Facebook)