I have a questions.xml file which has a list of questions for my quiz, and I'm trying to read this into a question bank in my program. I have written the following method:
// Creates the QuestionBank according to user requirements
public ArrayList<Question> createQuestionBank(String diff) {
int eventType = -1;
boolean FoundQuestions = false;
QuestionBank = new ArrayList<Question>();
// Find Question records from XML
System.out.println("check 1");
while (eventType != XmlResourceParser.END_DOCUMENT) { // Keep reading until the end of the xml file
System.out.println("check 2");
if (eventType == XmlResourceParser.START_TAG) {
System.out.println("check 3");
String Name = questionList.getName();
if (Name.equals("question")){ // Check whether the tag found is the one for question
System.out.println("check 4");
// Check difficulty of question
String diffCheck = questionList.getAttributeValue(null, "difficulty");
if (diff.equals("Any") || diff.equals(diffCheck)){
FoundQuestions = true;
System.out.println("check 5");
createandaddquestion();
System.out.println("check 6");
}
}
try {
eventType = questionList.next();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return QuestionBank;
}
I set some output statements to identify where my program was going wrong. The method outputs an endless cycle of check2 and never progresses to check 3, so is getting stuck at the statement:
if (eventType == XmlResourceParser.START_TAG)
I have adapted some code which I have found elsewhere and do not entirely understand what is happening. My understanding is that this statement finds the start part of a tag which I then progress to check whether this is the question tag which signifies the start of my question entry; what exactly is eventType though? Apparently it is an integer, but why does the XMLResourceParser.START_TAG return an integer when a tag is found? Surely it would make more sense to be a boolean? From the above post I don't think I need to stress that I am very new to android so please be patient! Thanks in advance.
It seems to me that eventType is never getting updated. I don't know enough about the specifics of XML parsing, but it seems that eventType needs to be updated, or else you will be stuck in an infinite loop, as you are currently being stuck. I'm guessing from looking at your code that you want to move this code down one set of brackets:
try {
eventType = questionList.next();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
That will make sure it is called during every loop of the while() command.
I use a Sax parser and it works great:
http://www.mkyong.com/java/how-to-read-xml-file-in-java-sax-parser/
You might find the Xerces2 API to be useful as well. It implements SAX and DOM parsing. http://xerces.apache.org/xerces2-j/
Related
I have a nested arraylist consisting of Productname and price within a while loop that Im trying to send to Apache POI Java program in eclipse to create a MS word invoice from my cart items. Problem is, only two items are being written into the word document and it seems the remaining function calls are not taking place to add further products and price. How do I fix this issue? Is there a way to reduce function calls? Im a beginner and this is a really important piece of code for my project. Please help
Here is my code:-
Iterator<ArrayList<String>> itr = bl.iterator();
while(itr.hasNext())
{
ArrayList<String> al = itr.next();
try {
n=z.writeData(al.get(0), al.get(1));
} catch (IOException e) {
e.printStackTrace();
}
try {
z.closeFile();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Runtime rt = Runtime.getRuntime();
try {
rt.exec("C:\\Program Files (x86)\\Microsoft Office\\Office12\\winword.exe C:\\Users\\kaustav\\Desktop\\"+n+".docx");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
my code to generate the product price and name-
public int writeData(String name, String price) throws IOException
{
paragraph=document.createParagraph();
paragraph.setAlignment(ParagraphAlignment.LEFT);
run = paragraph.createRun();
run.setFontSize(20);
run.setTextPosition(40);
run.setText(name+" "+price);
document.write(out);
return n;
}
the output should be that under Product name more than 2 items should be named and under Product Price their respective prices in my MS Word document but I only get upto 2 products and their prices. The remaining are not written into my MS Word document. Please help !!
I want to load a loop objects to the list, but I have a problem, because the loop is performed only once and the next loop crashes IOException line 'movie = (Movie) ois.readObject () ;'.
#SuppressWarnings("unchecked")
static <T> void loadDatabase(List<T> tab, int index) {
if(index == 1) {
try {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("movies.ser"));
try {
while(true) {
Movie movie = new Movie();
movie = (Movie) ois.readObject();
tab.add((T) movie);
}
} catch(EOFException ignored) {
ois.close();
}
} catch (FileNotFoundException e) {
System.out.println("Can not find the file. Please try again later...");
} catch (IOException e) {
System.out.println("Unable to save file. Please try again later...");
} catch (ClassNotFoundException e) {
System.out.println("The error of the projection class Movie");
}
} else if(index == 2) {
try {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("series.ser"));
while(ois.available() != 0) {
Series series = new Series();
series = (Series) ois.readObject();
tab.add((T) series);
}
ois.close();
} catch (FileNotFoundException e) {
System.out.println("Can not find the file. Please try again later...");
} catch (IOException e) {
System.out.println("Unable to save file. Please try again later...");
} catch (ClassNotFoundException e) {
System.out.println("The error of the projection class Series");
}
}
}
Lets dissect your (sorry, but horrible, horrible) code a bit:
#SuppressWarnings("unchecked")
static <T> void loadDatabase(List<T> tab, int index) {
if(index == 1) {
Dont do that. The whole point of index seems to be to distinguish what this method should do. Hint: create two methods instead; and avoid that parameter, and the if!
One method you would call loadMovieFromDataBase(); the other loadSeriesFromDataBase().
try {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("movies.ser"));
try {
while(true) {
Do you really want to loop forever?! That is what while(true) will.
Well, not forever, but until some exception will be thrown. So, even when your loop body would be doing the right thing (which it isnt!) ... that code must lead into some error condition.
Movie movie = new Movie();
movie = (Movie) ois.readObject();
That is like absolute nonsense. There is no point in calling new on a Movie object to have then read by an ObjectInputStream.
Movie movie = (Movie) ois.readObject();
is how you deserialize an object from an ObjectInputStream.
tab.add((T) movie);
}
} catch(EOFException ignored) {
ois.close();
Hint: you are a beginner. You have no idea what your code is doing; but you feel confident enough to ignore exceptions; not even trace them?!
And the following catches are not much better:
} catch (FileNotFoundException e) {
System.out.println("Can not find the file. Please try again later...");
} catch (IOException e) {
System.out.println("Unable to save file. Please try again later...");
You try to read a file. Hint: be careful when doing copy&paste of ERROR messages. This one doesn't make any sense here. Beyond that: don't replace the exception with some self-defined message. At least print the exception message, too. Because: your own code is all lying.
} catch (ClassNotFoundException e) {
System.out.println("The error of the projection class Movie");
}
No, the above error would mean that you tried to deserialize a class which does not exist in the context of the JVM that this code is running it.
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("series.ser"));
while(ois.available() != 0) {
Series series = new Series();
series = (Series) ois.readObject();
Same story as above. And hint: don't query the stream if more input is there. Just serialize one list of Series objects; than you just de-serialize one object later on.
The reason why I spent my time here: it seems that you are blindly putting together code without the slightest idea what that code is doing. That is, well a bad idea.
You better step back and read & run good tutorials on serialization. And only when you are able to run and understand that part, you try to come up with your own code.
Actually it is bad idea. best is deserialization once, clone and add to list how many time u wants.
I am reading datas from a csv file and set all datas into an object.At a particular point i am getting a numberformat exception (only after reading some datas)because some datas are not numbers(That is an error inside file some charecter datas in place of numerical datas,not able to use string concept because of some integration issues with main program).At that point i need to skip that line and need to move to the nextline.Can anyone please help.Any help will be highly appreciable.
reader = new CSVReader(new FileReader(parentPath+File.separator+file),',','"');
while ((nextLine = reader.readNext()) != null &&nextLine.length!=0 ) {
encap.setPrice((nextLine[5]));
String mrp=encap.getPrice().split("[,]")[0];
try {
encap.setProduct_price(Double.parseDouble(mrp));
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Note:I need to skip and read next line onwards when ever numberformat exception occurs for a particular line.(value is getting correctly but my program stops whenever a numberformat exception occurs.......
encap is the object of my class....
Expand the scope of your try catch. Brute force, put try just below while and include ALL code in that while block inside that try block.
It looks like your try..catch is already in the right place. Just make a new encap for each record and it should behave as you want:
List<Encap> encaps = new ArrayList<Encap>(); // <- create list of results
reader = new CSVReader(new FileReader(parentPath+File.separator+file),',','"');
while ((nextLine = reader.readNext()) != null &&nextLine.length!=0 ) {
Encap encap = new Encap(); // <- create a new instance for this line
encap.setPrice(nextLine[5]);
String mrp=encap.getPrice().split("[,]")[0];
try {
encap.setProduct_price(Double.parseDouble(mrp));
encaps.add(encap); // <- add this result to the list only if parsed ok
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I am getting the FFT back on an audio file, but it doesn't take into account the time in the song that that frequency occurred. I first tried getting the length of the file, and then spreading the FFT results equally over the track length, but that might be wrong and not give the correct frequencies back. So now I am trying to get the file split up into 1 second chunks and then return the frequency for that second alone, and then I will store that in a database to save it.
But I have no clue on how to save it, all other threads I have found and research I have done only shows how to break into x amount of parts, not per second as in a song. Is there a way to do this?
Sorry if this is a trivial topic, but I am very new to Java and programming, so this is quite a struggle for me.
Thanks in advance
Here is my code so far:
File file = new File(FILENAME);
float durationInSeconds = 0;
Tag tag;
java.util.logging.Logger.getLogger("org.jaudiotagger").setLevel(Level.OFF);
AudioFile audioFile;
try {
audioFile = AudioFileIO.read(file);
System.out.println("Track length = " + audioFile.getAudioHeader().getTrackLength());
durationInSeconds = audioFile.getAudioHeader().getTrackLength();
} catch (CannotReadException | TagException | ReadOnlyFileException
| InvalidAudioFrameException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
convert();
System.out.println(((durationInSeconds)/endResult.length)*1000);
for(int i = 0; i < endResult.length; i++) {
Thread.sleep((long) (((durationInSeconds)/endResult.length)*1000));
System.out.println(endResult[i]);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
folks. I'm trying to write to a file from a stack. The stack was created by reading from another file. I'm using the stack so that I can reverse the file I read in. The file names to read and write to are from the command line.
This is how I have my stack implemented:
while(read.hasNext()) {
stack.push(read.next());}
The code for my other file that the stack is supposed to write to:
FileWriter w = null;
try {
w = new FileWriter(new File(args[1]));
} catch (IOException e) {
e.printStackTrace();
}
if (!stack.isEmpty()) { //this was a while statement
try {
w.write(stack.pop());
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("Didn't make it.");
}
The problem that I'm having is when I run my program, the file I want to write to is created, but nothing gets written to the file. I originally thought that my stack didn't have anything in it (that's why I changed my while statement to an if; it's temporary). The "Didn't make it." didn't print so I now know it's not that. What am I doing wrong here? Any help is appreciated.
After w.write(stack.pop()); call the fush() method:
w.write(stack.pop());
w.flush();
and you can return the while statement. At the end call w.close();
the method stack.pop returns an Object if you do not specify at the time of declaration like this
Stack<String> stack = new Stack<String>();
and after writing you should use w.flush() and also you should use the w.close.
you should nest the while statement itself into the try block
for instance
try {
while(!stack.isEmpty()) {
w.write(stack.pop()); // assuming you have declared it as Stack<E>
}
w.flush();
w.close();
} catch(IOException e) {
e.printStackTrace();
}
EDIT:
after you are done with FileWriter when you close it, that has to nested inside a try catch block to catch any IOException if thrown. if you use the w.write() method inside the try catch block that is within the while loop then after the while loop iteration is over you have to build another try catch to place w.close()