Adding list in formatted way? - java

I'm bukkit python/jython coder, but I'm struggling adding my list to config. Since I can't get it to work with Bukkit API, I got idea to do it on more Pythonic way. I know how to write files using this format (for example):
fo = open("%s/TwistedJobs/config.yml"%pluginlocation2, "wb")
fo.write("Farmers:")
fo.close
I have config YAML file, in which I want to store player names with their job, here's example:
Farmers:
- Player
- Player1
Miners:
- Player2
- Player3
Traders:
- Player4
- Player5
Now I want to add players upon an event to list. For example, Farmers list. There is no problem with fetching player names and triggering event, that is not problem. Plan is to get that arraylist and add another player name there (I've done that already). Now I want to add that new arraylist in config, but how? They must be in format given above (config example)...
This is how I fetch arraylist and add new players to same list (it's working perfectly, but I don't know how to put that new list into config, since I can't get BukkitAPI way to work):
list = pyplugin.getCfg().getStringList("Farmers")
list1 = list.add(event.getPlayer().getName())
Thanks in advance, Amar!

No idea about the Bukkit API, but a list in python usually must me appended:
list.append(event.getPlayer().getName())
Also putting some traceback or errors might help anybody trying to answer your questions.

Related

Is there a way to create an ArrayList under certain circumstances?

I'm sorry if the question is phrased weirdly, but I wasn't quite sure how to fit it into the title space. I'm making a mini messaging program in which users create and log into accounts and send and receive messages. Is there a way to create an ArrayList of the user's messages when they create an account? All of the usernames are in another ArrayList, so maybe it can create one for every addition? I have the passwords and usernames in two different lists linked by position, so that could work too if it's even possible.
PS - I also need to be able to pull out and match the ArrayList to usernames, but that will come later.
I can clarify in the comments and show my code if you need it.
Thanks!
It sounds like you are looking for a data structure to store a list of messages per user. You can use a Map<User, List<Message> for this. When loading/adding a User, you can create an empty ArrayList<Message> and put it into the map for later use.
// Create map.
Map<User, List<Message>> userMessageMap = new HashMap<>();
// Insert new list for new user.
userMessageMap.put(user, new ArrayList<>());
// Insert message for existing user.
userMessageMap.get(user).add(message);
// Get all messages for an existing user.
List<Message> messages = userMessageMap.get(user);
The Answer by Pieter12345 is correct and smart.
Here is a table graphic I made to assist you in choosing an implementation of Map from among those bundled with Java. All of these support the operations seen in that other Answer.
Third-parties produce may produce Map implementations as well, such as Eclipse Collections or Google Guava.

Working with multiple ID's

I am creating a project in which I prompt the user with a table. And he has to fill in the values. And when he clicks on submit, at the back end I have to check all those values are correct or not.
Here is a sample pick of the table and code
As you can see i have given the id's as "fcfs_p1_ct" for p1 and "fcfs_p2_ct" for p2. Now at the back end when I have to check the values entered by the user. I have to create objects of the respective Edit Texts.
Now one way is to create n number of if else conditions and create the objects for each edited text manually. Can this process be done through loops?
For example for p1
String str = findViewById(R.id.fcfs_p1_ct).getText().toString;
similarly for p2
String str = findViewById(R.id.fcfs_p2_ct).getText().toString;
and so on for n number of processes.
As the only changing variable in the statements is the process number. Please suggest me a way to do the same for a loop
This kind of situations in android are not handled by loops, once you realize that your layout (XML) requires lots of View id assignments, it's recommended to use an Adapter. There are many ready-to-go Adapters available in android SDK, such as ArrayAdapter, BaseAdapter, CursorAdapter etc.
Which Adapter to choose depends entirely on your choice of View/layout you wish to inflate and the data type and source you're willing to use.
In your situation, I'd recommend starting with a simple ListView, and using a custom Adapter (class that extends BaseAdapter). There are many tutorials out there on how to implement this, which are by the way quite easy to follow.
You can simply keep these ids in an ArrayList of Integer like;
ArrayList<Integer> ids = new ArrayList<>();
ids.add(R.id.editText1);
ids.add(R.id.editText2);
When the user presses submit, you can go through that array and do what you want. If you would like to change the corresponding value at the end, you can keep a Map instead of ArrayList.
But my personal suggestion is that using a ListView or RecyclerView. You can repeat views with an Adapter and keep your data as instances of a class so that you can avoid these kind of codes.

Setting List<E> files in location for later use

I'm working on some kind of a game. There are default values that don't change and are stored in a list. My question is, is there a way to make a list once and add it to the app files so if I need the list all I need to do is List<E> new = mylist? or something along those lines? I could work with arrays if needed but preferably lists.

Assistance needed with Java GUI working with ODFDOM

Ok, so as a little personal programming project I had been trying to make a program in the past which would (via a GUI) held to record data of item drops from certain stuff in a game (Guild Wars 2 if you're curious). The GUI is simple enough: JFrame containing two JLabels and JTextFields, to say what to input and well, the text fields to type it in. Basic GUI stuff. The inputs are the item name and the amount. Also, there are two JButtons, with a listener each to add items and subtract items and finally another JLabel to function as error message display.
The structure of the "mapping" of items to amount obtained is stored during the execution of the java program in a TreeMap.
I had been creating a crude, basic implemention, saving data to memory in a .csv file but I decided last night I wanted to rework the system. Thus, I got the idea of trying to "write" to a spreadsheet format, and I thought, "well why not OpenOffice? Consequently, I discovered the ODFToolkit API and such, specifically the ODFDOM tools have been of interest to me of course. So I had thought I had this stuff refactored (if that's the right term) well enough and that things would go smoothly but...here's my problem:
So, in the GUI I type some test input; "Rotten Egg" is a valid item (invalids make an error display in the window) and I put some positive integer (only possibly type of valid "amount") for the amount obtained. Now, the first time I do this, with a valid input like this it works fine, but if I try again with different input or the same it displays the error text that should show only when an invalid item is entered. I tried a few things at least to debug it looking through it, but I am at a loss as to how this horrible bug has been created.
I will link to pastebin for my own two classes here:
GUI class: http://pastebin.com/rEbFS27j
Other class i.e. the Map structure and other stuff going on "behind" the GUI: http://pastebin.com/BWA4SUY0
sigh I figured it out eventually. I have this loop in the method that writes to the spreadsheet.
while (it.hasNext() == true) {
Map.Entry pairs = (Map.Entry)it.next();
odt.getTableList().get(0).getCellByPosition("A" + i).setDisplayText((String) pairs.getKey()) ;
odt.getTableList().get(0).getCellByPosition("B" + i).setDisplayText((pairs.getValue().toString())) ;
it.remove(); // avoids a ConcurrentModificationException
i++ ;
}
The line it.remove() ("it" is an Iterator variable) is a fatal error...an unfortunate remnant from a copy-paste when I looked up stuff in the past about how to use iterators... :/ Indeed it was the cause of this horrid "only works once" kind of bug. Guess I just really need to make sure I'm not using something wrong or unnecessary when I paste snippets of someone else's code into my work...

Need help creating a Quiz App for Android w. HashMaps & No Database

My assignment is to create a simple Quiz app for Android. I am NOT looking for the code for this.. I am simply looking for someone to possibly lay out how to get started with this (pseudo-code ish).
The program is suppose to display one term and four definitions; one of them being the correct one. Once the user selects which one they think it is, the program will tell the user if it was correct / incorrect using a toast message.
Specs:
The terms need to be randomly selected, and only displayed once per run. However the definition needs to stay in the pool of definitions for other questions.
Definitions randomally selected (except the right one)
Program ends if it runs out of terms to display
Needs to use an ArrayList to hold collections of items, and a HashMap to hold name-value pairs.
Must use Androids logging mechanism to log error messages (via try/catch statements).
If you can help me out by guiding me in the right direction, that would be great :) Thanks!
I would (as always in object-oriented languages) start by mapping your problem to real-live objects. In your case, there would be two:
A Question-class which holds four answers, the question and offers a method to check if the given answer was correct.
An Answer-class which holds a single answer and whether it's correct or not.
As for your storage question, I wouldn't use a HashMap at all. Store the Question-instances in an ArrayList and use a Random.nextInt()-method to get a random question from your list.
In your Question-class, you would store all possible answers in another ArrayList. To randomize the order in which the answers are presented, you can use the Collections.shuffle()-method.
For the presenting part, have your Question-class return the question (string) and the four answers (strings) and put the into your widgets. To identify the answer given, you can use the Answer-instance (using the array-index is easier, but it is more error prone).
To check if the right answer was given, query your Question-classes isCorrect(Answer)-method and check if the given instance in the internal ArrayList is marked as the correct one.

Categories