ArrayList and Formatter not behaving as expected - java

I have two Arraylists, one contains an entire list of objects, the second contains objects to remove from the first list.
When I remove the objects from the first list and when I output those objects to a file using a Formatter, nothing is written to the file. However if I output the objects from the first Arraylist, without removing any objects, all of those objects appear in the file.
For example:-
for(Invoice inv : tempStore)
{
if(invoiceLines.contains(inv))invoiceLines.remove(inv);
}
//for each invoice in the ArrayList
for(Invoice invoice : invoiceLines)
{
output.format("%"+this.spec.getLength("XXXX")+"s\t",checkString(invoice.getInvoiceDate()));}
gives me no output, however doing just:-
//for each invoice in the ArrayList
for(Invoice invoice : invoiceLines)
{
output.format("%"+this.spec.getLength("XXXX")+"s\t",checkString(invoice.getInvoiceDate()));}
gives me output information, when manually debugging the application the arraylist (the one with the objects removed), does contain objects still and those objects contain the correct values. It's almost as if the Arraylist, once objects are removed is losing the pointers in memory.
Any ideas? Unfortunately I can't give much in the way of specific code, however ask any questions and I will try to answer as best as I can. The language is Java and I'm using Java compliance 1.5 in the SDK.

To identify the error you can add more output (as console output or using a Logger) on the removing operation:
System.out.println("Items before removal: " + invoiceLines.size());
for(Invoice inv : tempStore)
{
if(invoiceLines.contains(inv)) {
invoiceLines.remove(inv);
System.out.println("removed " + inv + ". Items left: " + invoiceLines.size());
}
}
If there are more than items removed during one iteration, you want to check the equals() and hashCode() Implementation of the Invoice class.
If you have your own implementation, make sure you followed the Object.equals()-Contract.

Formatter.flush() and Formatter.close() need to be called at the end of output.

Related

does bufferedWriter require getters

Hi i know the use of getters is to restrict access. The issue is i have a buffered writer that is using some information in another class. Therefore using getters i have gotten that information and written into a file using the bufferedWriter.
The issue comes when i am trying to use some information in the same class as the bufferedWriter. It doesnt write those details . Shows no error in the code either just doesnt write it. If the data is in the same class as the buffered writer i assume that it doesnt need to be accessed using getters? although the values are stored in another method. Explain this
Thank you alot
bufWrite.write("Your Character Class:" + character_Class + "\n");
bufWrite.write("Your Character Level:" + level + "\n");
The character class and level here are from 1 class called character. To access these information i have used getters (Since the buffered writer is inside another class.Basically i have 3 classes. Character details in one and i am using the bufferedWriter which is in a different class to store these details into a file.)
These details are written into the file completely.
for(Object o:skillInfo){
bufWrite.write("" + o + "- Rank(skill Points) :" + rank);
}
i am trying to use this foreach loop to write stuff inside a linkedlist. This linked list is inside the same class as the buffered writer statements are. But this doesnt get written while the other details(as listed above) get written. The only difference is that those details are using getters since they are not in the same class as the bufferedWriter is while the linked list is in the same as the bufferedWriter thus doesnt use a getter.
I hope this is clear enough
**Update
Also please note that the character.Level and the rank are user entered values.
To answer your question, a BufferedWriter by itself does not 'require' getters.
If your BufferedWriter is not writing data, then the problem might be how you are actually writing the data. You also might want to check if you are calling .close() when you are done writing the data.
Another problem might be how your data is returned from the get-er.
Your question is rather ambiguous, so any answer can only be a guess. I recommend reading up on how to make a good question, so that people can provide better answers.
https://stackoverflow.com/help/how-to-ask
https://stackoverflow.com/help/mcve
*Edit:
Thank you for updating your question.
If you want to write out the details of character_Class, you do need to call the getters of the specific information that you want to get from the class.
The reason why bufWrite.write("Your Character Class:" + character_Class + "\n"); doesn't throw an exception or crash is because of how java coerces classes to String.
The line of code:
"Your Character Class:" + character_Class
is the same as:
"Your Character Class:" + character_Class.toString()
Same happens with objects from skillInfo:
bufWrite.write("" + o.toString() + "- Rank(skill Points) :" + rank);
Basically, if you concatenate '+' a String and an object, it calls toString() on the object. If you concatenate a String and a primitive type, it just converts them to Strings first.

Looping through 2 String Lists

I wanted to know how I could possibly loop through 2 string lists (array lists - Bukkit) to see if I can find the value I need. Currently I have:
for (String parent : fc.getConfigurationSection("generators").getKeys(false)) {
for (String ls : fc.getStringList("generators." + parent)) {
}
}
I then check if the value in 'ls' is equal to the value I am searching for. I see that using 2 for loops is bad practice which is one of the many reasons that I have been trying to find a way around.
My User File:
generators:
262d327f-34e3-42be-87f5-235068661f30:
- Spawn,0,60,-249,Common
Notice how they are player UUIDs followed by a location which is automatically saved, I wish to check if a value in the list is equal to the one I want before returning the parent (UUID) to find who that belongs to.
Hopefully I've made myself clear what I have been trying to approach.

How can I add (+) an integer to an element in a 2-dimensional ArrayList?

I'm trying to add 1 to an integer in a 2-dimensional ArrayList.
I'm using the set() method with the element + 1 as the second argument, but the "+ 1" isn't working. When I retrieve the element, it defines it as an object, not an integer. How do I get around this?
Code:
ArrayList<ArrayList> inventoryList = new ArrayList(
Arrays.asList(new ArrayList<String>(), new ArrayList<Integer>()));
...
(inventoryList.get(1)).set(i, ((inventoryList.get(1)).get(i) + 1));
Error:
Main.java:47: error: bad operand types for binary operator '+'
(inventoryList.get(1)).set(i, ((inventoryList.get(1)).get(i) + 1));
^
My code is at this ideone page. This code is translated from python and I'm currently debugging it so don't worry about the other errors.
ArrayList<ArrayList> inventoryList = ...
You are using the raw variant of ArrayList for your inner lists, such an ArrayList indeed contains Objects instead of Integers. You shouldn't use those raw ArrayLists and instead use generic ones:
What is a raw type and why shouldn't we use it?
Looking at your code a bit more, it seems that inventoryList is supposed to contain two lists, one that contains the items you have (as strings) and one that contains how many you have (as integers) where you can find how many you have of the item at index i in the first list by looking in the second list at that same index i.
If that is correct there are multiple ways to fix this, indeed, casting the Objects to Integers works, but then you are still using raw types, which you probably shouldn't. To fix this you should just not keep the ArrayList<String> and the ArrayList<Integer> in the same list. You could just have:
ArrayList<String> inventoryItems = ...
ArrayList<Integer> inventoryItemCounts = ...
separately (you don't need a list if it always contains exactly 2 items, a list of strings and a list of integers). However a cleaner solution would be, as was suggested in the comments by user2418306, to use a map
Map<String, Integer> inventory = ...
http://docs.oracle.com/javase/7/docs/api/java/util/Map.html, that way each string (item) in your inventory has exactly one corresponding integer (number you have of that item) and you don't have to get that by using the "at the same index" trick.
Looking at you code a bit though, I would say that more is going wrong with the inventory. You print your inventory using:
for (int i = 0; i < inventoryList.size(); i++){
System.out.println((inventoryList.get(1)).get(i) + " : " + (inventoryList.get(0)).get(i));
}
and you iterate through it in that way in other places as well. However, if i'm not misunderstanding anything, inventoryList.size() is always going to be 2 (the inventoryList contains 2 lists, one of strings and one of integer). To get the number of distinct items (strings) in your inventory you'd have to do inventoryList.get(0).size() (or inventoryList.get(1).size() because that is going to be the same). However, things will get easier if you chose a better datatype for your inventory. I would look into the mentioned Map. Using that, you easily get the correct number using inventory.size().
You can solve your problem by casting to Integer
inventoryList.get(1).set(i, (Integer) inventoryList.get(1).get(i)+1);
Of course first take a look on comments below your question to see how to properly init your list, so you wont need explicit cast.
The way it is declared, your lists are list of Object. You need to cast the result from second get() with (Integer), like:
inventoryList.get(1).set(i, (Integer)inventoryList.get(1).get(i)+1);
Note: There are unneeded ().

List lettering and bulleting problems in iText in Java

How come this works:
lA = new List(List.ORDERED, List.ALPHABETICAL);
lA.setLowercase(List.LOWERCASE);
lA.setPostSymbol(") ");
but this doesn't:
lQL = new List(List.UNORDERED);
lQL.setListSymbol("=");
lQL.setPostSymbol(" ");
?
In the first example in front of every item is "a) " or "b) " or "c) " etc...
In the second example in front of every item is only "=".
Before any ideas, two things. Firstly, I can't do it this way: lQL.setListSymbol("= ");. I could explain it, but just go with it, it's simpler. Secondly, I tried setting second string to "k " (so it's not only spaces), but the output was still "="...
What's happening?
Because you have explicitly indicated that you want an unordered list with List.UNORDERED. Thus, you'll not get any order for your items, and therefore the post symbol will not be used.
From the documentation of setPostSymbol:
Sets the String that has to be added after a number or letter in the
list symbol.
And from the source code of List:
137 /**
138 * In case you are using numbered/lettered lists, this String is added after the number/letter.
139 * #since iText 2.1.1
140 */
141 protected String postSymbol = ". ";
This number or letter will only be added for ordered lists, i.e., List.ORDERED. If you inspect the first argument of the constructor of List, you'll see that it receives a boolean to indicate if the list is numbered or not. Since you are passing it List.UNORDERED, whose value is false, you won't get a numbered list, and thus, postSymbol will not be appended.
To set or unset number ,letter or bullet use the following single code for List with usage of iText pdf out or simply with list.
For example,for List with no bullet or string or number usually required in printing bills.
List list = new List(false, false, 50);
list.setListSymbol(" ");
Thank you for your queries..

why this code about combobox doesn't work?

I have a combobox which stores "Computer ,Code:21","History ,Code:31" and also the number of items can be changed.but when I write this code for getting its items:
List<String> bIHELessons = new ArrayList<String>();
for (int i=0;i<jComboBox1.getItemCount();i++) {
String lessons = (String) jComboBox1.getItemAt(i);
if (lessons != null&& lessons.trim().length()!=0) {
bIHELessons.add(lessons);
System.out.println(bIHELessons.toString());
}
}
it will show these sentences in the console:
[Computer,Code=21]
[Computer,Code=21, History,Code:31]
Because you are appending to the list with bIHELessons.add(..). Each subsequent call adds on to the already printed string.
If you want to still add to the ArrayList and print the current item that is in the ArrayList, then use System.out.println(bIHELessons.get(i)); rather than using what you are now. I also don't think you need to use toString() because your objects are already in the type string.
Change System.out.println(bIHELessons.toString()); to System.out.println(lessons); if you only want to print the string you are currently iterating on.
From what I can see your code is doing what it should be doing. Are you wanting to know why you are seeing all items repeated with each additional call to the print screen?
That is happening because the toString() method of the List is putting all the items in the list into a single string.
I don't think the problem is with JComboBox but rather with your expectations. System.out.println(bIHELessons.toString()); will print out the entire contents of the bIHELessons ArrayList. Since you're adding a new String to the ArrayList on each iteration, it's logical that your System.out.println(bIHELessons.toString()); would show a progressive accumulation of content.
Your question isn't clear but you may consider moving the System.out.println outside of your loop and determining if that's what you're looking for.
You are printing out the ToString() representation of your entire list. If you want to print out the object you could just print out the lessons variable instead.

Categories