Java: Add to array by JOptionPane - java

I have this array:
String[] countriesList = {
"Japan",
"Sverige",
"Tyskland",
"Spanien",
"Syrien",
"Litauen",
};
I want to be able to add another thing to the array, in this case this [6]th position. Is it possible to do this by JOPtionPane? This is what I've done this far, however nothing happens nor does any errors occur.
String addland = JOptionPane.showInputDialog("Vilket land vill du lägga till?").trim();
countriesList[6] = addland;

Arrays start their counting from 0, so you could use countriesList[5] = addland;
You may use a dynamic list to perform your task.
They are better in every situation and should be superior to simple Arrays
Try to use this
List<String> countriesList = new ArrayList<>(
Arrays.asList("Japan", "Sverige", "Tyskland", "Spanien", "Syrien", "Litauen"));
String addland = JOptionPane.showInputDialog("Vilket land vill du lägga till?").trim();
countriesList.set(5,addland);
System.out.println(countriesList);
Output, after entering asdadsad:
[Japan, Sverige, Tyskland, Spanien, Syrien, asdadsad]
To add a land to the existing list use countriesList.add(addland); instead of countriesList.set(5,addland);

Related

Recall String Array by asking user for its Name

I'm writing a program that can grade multiple choice exercises for a class.
I wanted to store each answer key as a String array, and then have the user enter a String (the name of the exercise) which would be able to summon the stored String array. From there I know how to compare the stored String to the user's inputs.
I just have no idea how to take the input String and use it to summon the stored String array. Any tips?
thanks!
Using individual arrays to store each answer is grossly inefficient. What you need is an object that can store values which can be referenced by a key and a Hashmap provides just that. Study the illustration below:
//Declare your hashmap:
Map <String, String> myAnswers = new HashMap<>();
/*
*Put the values you want
*The put method takes in two parameters, the key and the value.
*The key represents the name you want to call this element by.
*The value is the actual value (so to speak)
*/
myAnswers.put("firstQuestion", "Answer of firstQuestion");
myAnswers.put("secondQuestion", "Answer of secondQuestion");
myAnswers.put("thirdQuestion", "Answer of thirdQuestion");
//You can go on and on: key, value.. Just like we did up there.
If you need the value of any of these keys, just do something like this:
myAnswers.get(firstQuestion);
I hope this helps.. Merry coding!
There are many ways to do this, it kind of all depends on your code design, but in general you can retrieve specific positions of any String[] by using a simple for loop (assuming this is a long test quiz):
class Grades {
Grades grades = new Grades();
String [] test1 = {"A", "B", "A", "C"};
for (int i = o; i < test1.length; i++) {
//this will retrieve every grade at every array position in order for 0 to
however long the array is.
grades.get[i]
}
}

adding a StringList element inbetween exisiting List items in processing

I am currently trying to parse a .txt file (subtitles file) to a .csv table.
Example out of the file:
22
00:03:36,717 --> 00:03:38,344
(thunder crashing)
I figured using the StringList Type was my best choice for that and I almost got all my information ready. The only thing left is, that I want the second line with the start pos. and the end pos. to be in seperate strings, following each other, like this:
22
00:03:36,717
00:03:38,344
(thunder crashing)
I already know how to do it with the substring() method, but I can't figure out how to add the new String at a specific index. the set function overwrites it and the appends function can only add it to the end of the list.
Is the use of an ArrayList better in hindsight? I tried doing that, but then I couldn't figure out how to use the actual element. What I have is this:
String s[] = loadStrings("subtest.txt");
ArrayList lines= new ArrayList();
for (int i=0; i<s.length; i++){
lines.add(s[i]);
}
which added all the lines in seperate elements of the ArrayList. Now I can't access the element as a string however. If I want to get the length of a specific element, it tells me that the length() function doesn't exist and I can't save the element as a string either.
Thanks for looking into it!
The problem is that, by default, ArrayList contains a list of Objects rather than a list of Strings, so the objects you get out of it will be of the wrong data type. Because the result of ArrayList.get() is an Object, you can't assign it to a String or call methods of the String class on it (such String.length()).
What you want are type generics. Because ArrayList is a generic class, you can use the generics syntax to specify the type of objects it should hold:
ArrayList<String> lines = new ArrayList<String>(); //creates a list of Strings
Processing provides a more complete example in their documentation of the ArrayList class.
Considering the XY problem, you probably need to replace " --> " with a new line, like this:
MainP:
public static void main ( String [ ] args ) throws IOException
{
Path path = Paths.get("yourFilePath.txt");
Charset charset = StandardCharsets.UTF_8;
String content = new String(Files.readAllBytes(path), charset);
content = content.replaceAll(" --> ", "\n");
Files.write(path, content.getBytes(charset));
}
Input:
1
00:00:00,000 --> 00:00:01,567
Anteriormente en Vikings...
2
00:00:01,765 --> 00:00:03,298
Voy a ir de nuevo a saquear Inglaterra,
3
00:00:03,300 --> 00:00:05,233
para la venganza de la
destrucción del asentamiento.
Output:
1
00:00:00,000
00:00:01,567
Anteriormente en Vikings...
2
00:00:01,765
00:00:03,298
Voy a ir de nuevo a saquear Inglaterra,
3
00:00:03,300
00:00:05,233
para la venganza de la
destrucción del asentamiento.
Note: This way you are overwriting the input file.

How to add elements from several arrays to a new static array without ArrayList?

For a school assignment, I have successfully created a program which stores recipes (name, ingredients, instructions). I now need to add a shopping list feature which will take the ingredients from the recipes I've added and store them in a new static string array.
I have been required to create the ingredients string array with a size of 20 and the shoppingList as a static string array with a size of 40:
private String[] ingredients = new String[20];
private static String[] shoppingList = new String[40];
I initialized all elements of both arrays to an empty string.
I've also hard coded two recipes in my test program like this:
rcp1.setIngredients(0, "Butter");
rcp1.setIngredients(1, "Garlic");
rcp1.setIngredients(2, "Parsley");
rcp1.setIngredients(3, "Bread");
rcp1.setIngredients(4, "Cheese");
rcp2.setIngredients(0, "Biscuits");
rcp2.setIngredients(1, "Pepperoni");
rcp2.setIngredients(2, "Pizza sauce");
This is where I get stumped:
public void setIngredients(int loc, String ingredient) {
ingredients[loc] = ingredient;
for (int i=0; i<shoppingList.length; i++){
if (shoppingList[loc] == "") {
shoppingList = ingredients;
}
}
}
Because the ingredients of rcp1 and rcp2 both use the ingredients locations [0, 1, 2], trying to add the ingredient to the static shoppingList using [loc] results in it overwriting those locations of the first recipe.
I've created the for loop so it could properly display the first recipe's ingredients; however, I'm not sure how to then proceed to find the location of the next empty string in order to list the ingredients of the second recipe. I was thinking that I would have to use an else if statement and then figure out a way to find where the next empty string is so I can begin to add the next recipe's ingredients from that point..?
Is there any other, possibly simpler, way that I could take the ingredients from rcp2 and place them after rcp1's ingredients in shoppingList?
I think I've been over-analyzing this problem and I haven't been able to find a solution yet, so I'd greatly appreciate it if anyone could point me in the right direction. Thank you!
You are running into a lot of artificial constraints, which is expected since this is a course assignment. Your main problem is that - apparently - you don't know how many ingredients are in each recipe, or in the shopping list. Normally, the array would be the right size for the contents so you would have the number of items in arr.length. Otherwise one would use one of the classes in the collections framework, like ArrayList.
However, you are using fixed-size buffers, which means that you need to track the current size of your list in addition to the capacity, which is what arr.length gives you. There are two ways you can do it:
Explicitly, by having an int variable that is conceptually associated with the array to mean "first unused element". When you add new elements, you would start at that index, and increment that variable for every new ingredient added to the list. This is what ArrayList does.
Implicitly, by having some kind of "marker" String that would mean "unused". This can be a proper String instance, or simply null. This is basically what C does with the '\0' string terminator.
Each option has different trade-offs and requires a different implementation, which I'm not adding here since you need do think about it as part of your course! Do not hesitate to ask more if you're stuck again, though.

Order values by separate string

Sorry about the non-descriptive title, I couldn't think of a way to explain it better short of 100 words. What I would like to be able to do is sort a list of strings into "boxes" based on a string associated with the main string and an array of strings "order".
For my current setup I am using a HashMap to store the string and it's associated "place-in-the-order" string.
I am aware that my explanation is truly crap so I have made an image which I hope will explain it better:
The variables are initialised as follows:
private final String[] order = new String[] {"Severe", "Warning", "Info"};
private final Box[] boxes = new Box[] {new Box(1), new Box(2), new Box(3), new Box(4)};
private final Map<String, String> texts = new HashMap<String, String>();
texts.put("Server on fire!", "Severe");
texts.put("All is good!", "Info");
texts.put("Monkeys detected!", "Warning");
texts.put("Nuke activated!", "Severe");
This shouldn't be too hard to implement but the only way I can think of doing it is by using 3 loops which seems a bit wasteful and would be slow if there was large numbers of any of the inputs.
Here is some example code which will hopefully show what I have come up with so far and perhaps explain the problem, I have not tested it and don't have an IDE handy so have probably overlooked something.
Set<Box> usedBoxes = new HashSet<Box>();
for(String curOrder : order) {
for (String text : texts) {
if (texts.get(text).equals(order)) {
for (Box box : boxes) {
if (!usedBoxes.contains(box)) {
box.setText(text);
usedBoxes.add(box);
break;
}
}
}
}
}
I'm not sure I fully understand what you want to achieve, but I feel that there are two things that would make your design much simpler:
Don't use Strings for your severity levels. Use enums instead. Enums have a name, may have other fields and methods, and are naturally ordered using their order of definition. And there is no way to make a typo and introduce an unknown severity: they're type-safe
enum Severity {
SEVERE, WARNING, INFO
}
Don't store things in parallel arrays or associate them with maps. Define a class containing the information of your objects:
public class Box {
private String text;
private Severity severity;
}
Now that you have these, you can simply create a List<Box>, and sort it using a Comparator<Box> which sorts them by severity, for example:
List<Box> boxes = Arrays.asList(new Box("Server is on fire", Severity.SEVERE),
new Box("All is good", Severity.INFO),
...);
Collections.sort(boxes, new Comparator<Box>() {
#Override
public int compare(Box b1, Box b2) {
return b1.getSeverity().compareTo(b2.getSeverity());
}
}
or even simpler, with Java 8:
boxes.sort(Comparator.comparing(Box::getSeverity));
You should make your "statuses" (Severe, Info etc) into an Enum.
public enum StatusLevel {
Severe,
Warning,
Info;
}
You can then sort by StatusLevel natively as long as you define the in a top to bottom order.
If you want to supply your Box object directly insead of pulling out the StatusLevel or have a secondary sort by another property like time or alphabetically you should implement your own Comparator
Also you may want to look into SortedMap or other Map that keeps its order so you don't have to resort a HashMap every time as it does not guarantee order.

Grab words out of arrays

I am extremely unsure of how to do this. I understand (I believe) that you use
String[] user {"stuff","other stuff","more stuff"};
I'm developing a chat bot and I need it to be able to recognize what the user said and if it's inside of the array (it's "database," per say), then it will respond accordingly.
Something simple so that I could be able to say, "How are you?" And it would look for "How are you?" or something at least close to it and respond accordingly with a random positive word. I've achieved this function by simply using lots of if-else statements, but this is far too much coding.
If I understand you correctly, you want your bot to respond to some prompt from the user. In that case, you could use a Map<String, String> to store query-answer pairs.
Map<String, String> answers = new HashMap<String, String>();
answers.put("How are you?", "Great!");
answers.put("Where is the cake?", "The cake is a lie");
and then just check whether the query string is in answers:
public String answerUser(String query) {
if (answers.containsKey(query)) {
return answers.get(query);
} else {
return "I don't understand.";
}
}
If you want more than one possible answer, use a Map<String, List<String>> and select randomly from the list:
public String answerUser(String query) {
Random rand = new Random();
if (answers.containsKey(query)) {
List<String> ans = answers.get(query);
int id = rand.nextInt(ans.size());
return ans.get(id);
} else {
return "I don't understand.";
}
}
This is a very big and complicated subject, and you haven't really posted enough to go on.
To split a string into words use String#split(), that will give you the array you want. (you probably want to split on all non-alpha, or all whitespace).
You then want to define keywords that your AI responds to, and scan the array for any of those keywords.
Use some sort of scoring system to then determine the appropriate response.
For example you could have a HashMap of String to a class that has both a weight and a meaning. Go through the sentence, sum up the scores for every action you find. Take appropriate decisions based on the combined values.
That's a very simple algorithm and much better ones are possible but they are a lot harder and this will get you started.
You could use a list instead of array, which will give you the contains() method. For instance:
List<String> words = new ArrayList<String>();
words.add("Hello");
words.add("bye");
if(words.contains("hello")) {
//do something
}
Another option would be to map the phrase to the response:
Map<String, String> wordMap = new HashMap<String, String>();
wordMap.put("How are you?", "Great");
wordMap.put("Where are you?", "Work");
wordMap.get("How are you?");
Combine these and map a phrase to a list of responses if you want.
An intelligent chat bot would need a lot more design, but if you just wanted a solution where "I say this, then you say that" than you could do it a couple ways.
Using Two Arrays
Since you know how to use one array, Figured I'd start here for simplicity.
String[] userInput {"how are you", "how are you?", "how you doing?"};
String[] response {"good", "terrible", "is that a joke?"};
//Go through each userInput string and see if it matches what you typed in.
//If it matches, print the corresponding position in the response array.
Using a Map
Same idea, but is a collection that is more suited for the situation.
Map<String, String> response = new HashMap<String, String>();
response.add("how are you", "good");
//When you receive input, check the response map using the input as the key.
//Return the value as the response.
//Better documented in sebii's answer.

Categories