Creating function to have parameter to create multiple JRadioButton - java

I am trying to create a java function where it takes 2 parameter. One is comma delimited list of string that represent what will be called for radio button. Second is comma delimited list of string that represents the variable respected to 1st parameter.
For example, If I write f1("apple,banana", "a,b"), I wanted to make JRadioButton with apple and banana along with a and b being their variable.
Is this possible?
I tried to use split(",") but I did not get too far...
Thanks in advance!
EDIT: I came up with following but still now luck..
static void f5(String question, String rbLabel, String rbVar, String help)
{
JOptionPane.showInputDialog(question);
ArrayList<String> rbLabelAL = new ArrayList<String>();
ArrayList<String> rbVarAL = new ArrayList<String>();
String[] token;
String[] token2;
token = rbLabel.split(",");
token2 = rbVar.split(",");
if(token.length == token2.length)
{
for(int i=0;i<token.length;i++)
{
rbLabelAL.add(token[i]);
rbVarAL.add(token2[i]);
}
}
JRadioButton(rbLabelAL(0));
}

Following up on my comment....if you wanted to do something like this, I would suggest creating an arraylist.
Something like.... ArrayList<String> options = new ArrayList<String>();
Add in your options....options.add("apple");
Then pass the arraylist into your method and create the radio buttons as such...JRadioButton(options(i));
Of course you would have to iterate through the list to create all buttons.

Related

how to check contains in arraylist or set

I have two Strings
String first = "value=[ABC,PQR,XYZ]"
String second="value=[ABC]"
I am trying to check the contains of string second into a string first.
I am using the below code
List<String> list = new Arraylist<>();
list.add(first);
if(list.contains(second)){
// do something
}
How to check contains in the list which has string with multiple ","?
Which data structure should I use for above problem?
Probably, you don't know how to work with lists in java...
In your case, you are adding a string "value=[ABC,PQR,XYZ]" to the list. Hence, you have a list with only one item.
If you want to create such a list ["ABC","PQR","XYZ"], you have to add these three elements one by one.
P.S. If you studied java basic, you wouldn't have such problems...
String first = "value=[ABC,PQR,XYZ]";
String second ="value=[ABC]";
String secondVal = second.substring(second.indexOf("[") + 1, second.indexOf("]"));
String[] firstArry = first.substring(first.indexOf("[") + 1, first.indexOf("]")).split(",");
boolean secondInFirst = false;
for (int i = 0; i < firstArry.length; i++) {
if (firstArry[i].equals(secondVal)) {
secondInFirst = true;
break;
}
}
I'm not sure why the first and second are formatted in such a way, however, assuming they are always formatted the same way ("value=[X,Y,Z]"),
We must break first up into a fixed list ("value=[ABC,PQR,XYZ]" -> {"ABC","PQR","XYZ"})
Format second to be readable ("value=[ABC]" -> "ABC")
Loop through firstArry and find matches
Store the result in secondInFirst

Using arrays of arrays as pointers to expandable lists of classes in Java

Reading the first answer in the Passing a String by Reference in Java? I (as on old pointer freaked C nerd) have a question regarding using arrays as pointers in java.
I have a variably number of EditText boxes in a setup routine for a n number of strings to be stored. This includes a add one EditText box button. So on screen the button is followed by a n number of EditText boxes. I have a similar for URLs to be stored.
Instead of having the same like 20 lines of code repeated over and over again for different such setup data items it is quite obviously a case for a method (function in C) and the issue is how do I keep the information about what EditText boxes are created when the user is pushing the Save button. In C you just send a pointer of an array of editboxes and realloc the editboxes array if new editboxes are created. In Java I can't realloc a the editboxes array to expand it but can create and clone it. But then it is not the same the editboxes array. But then I have the old editboxes array in the calling method and not the new. But obviously with Strings it is possible to make a String array array of one unit and send to the method and get it updated. This is obviously possible to be used with editboxes arrays as well, making an editboxes array array of one editboxes array that could be updated by the called method and expanded.
String[][] stringList = new String[1][];
stringList[0] = new String[2];
stringList[0][0] = new String("Sonny");
stringList[0][1] = new String("Ronny");
ExpandArray(context, stringList);
public static void ExpandArray(Context context, String[][] stringPtr) {
stringPtr[0][1]="Zeke";
String[] strings = new String[3];
System.arraycopy(stringPtr[0], 0, strings, 0, stringPtr[0].length);
stringPtr[0] = strings;
stringPtr[0][2]="Sue";
}
and
EditText[][] EditTextList = new EditText[1][];
EditTextList[0] = new EditText[2];
EditTextList[0][0] = new EditText(context);
EditTextList[0][1] = new EditText(context);
ExpandArray(context, EditTextList);
public static void ExpandArray(Context context, EditText[][] EditTextPtr) {
EditText[] EditTexts = new EditText[3];
System.arraycopy(EditTextPtr[0], 0, EditTexts, 0, EditTextPtr[0].length);
EditTextPtr[0] = EditTexts;
EditTextPtr[0][2]== new EditText(context);
}
Question 1 Reading the first answer in the Passing a String by Reference in Java? all comments are in strong favour of the two first StringBuilder solutions, but with no explanation why. That is Strings here we are talking about class arrays, might be different. *I feel I just made a C-solution in Java syntax and there might be some better Java culture solutions? You know C nerds are crazy about pointers to pointers etc and this smells such. *
Are there any better solutions for class arrays than arrays (solution 3)?
I am learning Java culture and my actual method of a button and n number of EditText boxes (works fine), but feel like garage culture:
public static LinearLayout TextListbox(Context context, EditText[][] EditTextboxes, String Title, String DataStringsDimension) {
final Context contextTextListbox = context;
final EditText[][] EditboxTextListbox=EditTextboxes;
final String ItemText = Title;
final LinearLayout layoutEditTextListbox = new LinearLayout(contextTextListbox);
layoutEditTextListbox.setOrientation(LinearLayout.VERTICAL);
layoutEditTextListbox.setX(layoutEditTextListbox.getX() + 15);
layoutEditTextListbox.setBackgroundColor(Color.rgb(0xFF, 0xE8, 0xAA));
if (DataStringsDimension != null)
EditboxTextListbox[0] = new EditText[getJniListDataSize(DataStringsDimension)];
else
EditboxTextListbox[0] = new EditText[0];
final Button button = new Button(contextTextListbox);
button.setText("+ " + ItemText);
button.setTag(EditboxTextListbox[0].length);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Enlarge to Edit box array
EditText[] EditboxArrayTemp = new EditText[EditboxTextListbox[0].length + 1];
System.arraycopy(EditboxTextListbox[0], 0, EditboxArrayTemp, 0, EditboxTextListbox[0].length);
EditboxTextListbox[0] = EditboxArrayTemp;
// Register a new edit box
EditboxTextListbox[0][EditboxTextListbox[0].length - 1] = new EditText(contextTextListbox);
EditboxTextListbox[0][EditboxTextListbox[0].length - 1].setHint(ItemText);
EditboxTextListbox[0][EditboxTextListbox[0].length - 1].setInputType(InputType.TYPE_CLASS_TEXT);
layoutEditTextListbox.addView(EditboxTextListbox[0][EditboxTextListbox[0].length - 1]);
}
});
layoutEditTextListbox.addView(button);
if (EditboxTextListbox[0].length > 0) {
String[] DataStrings = getJniTextUnceListData(DataStringsDimension);
for (int iSlotTitle = 0; iSlotTitle < EditboxTextListbox[0].length; iSlotTitle++) {
EditboxTextListbox[0][iSlotTitle] = new EditText(contextTextListbox);
EditboxTextListbox[0][iSlotTitle].setText(DataStrings[iSlotTitle]);
EditboxTextListbox[0][iSlotTitle].setTag(DataStrings[iSlotTitle]);
EditboxTextListbox[0][iSlotTitle].setHint(ItemText);
EditboxTextListbox[0][iSlotTitle].setInputType(InputType.TYPE_CLASS_TEXT);
layoutEditTextListbox.addView(EditboxTextListbox[0][iSlotTitle]);
}
}
return layoutEditTextListbox;
}
Question 2 It certainly be improved as Java culture? Any smart ideas?
I have it as a method in the SetupDlg class of mine, any reason to make such a thing its own class?
There might be some better ideas of how to make a setup edit for n number of text strings to be edited?
You can just use ArrayList instead of Array. Array has a fixed size, but ArrayList can grow easily. Equivalent to this:
String[][] stringList = new String[1][];
stringList[0] = new String[2];
stringList[0][0] = new String("Sonny");
stringList[0][1] = new String("Ronny");
ExpandArray(context, stringList);
public static void ExpandArray(Context context, String[][] stringPtr) {
stringPtr[0][1]="Zeke";
String[] strings = new String[3];
System.arraycopy(stringPtr[0], 0, strings, 0, stringPtr[0].length);
stringPtr[0] = strings;
stringPtr[0][2]="Sue";
}
will be:
List<List<String>> stringList = new ArrayList<List<String>>();
stringList.add(new ArrayList<String>());
stringList.get(0).add(new String("Sonny"));
stringList.get(0).add(new String("Ronny"));
ExpandArray(context, stringList);
//Instead of expand array
stringList.get(0).add(new String("Sue"));
For editText just use:
List<List<EditText>> editText = new ArrayList<List<EditText>>()
The size of ArrayList increases as required.
And about passing by reference, in java everything is passed by value. Only class objects are passed by reference. So only if you pass a class object and modify it, the change will be reflected outside the function.
For strings you can use string builders or String objects but if its only one string following works as well:
void main(){
string txt = "foo";
txt = addString(txt);
System.out.println(txt);
}
String addString(String txt)
{
txt += " bar";
}
The output will be : foo bar
Hope this helps!!

Convert a List of objects to a String array

I have the below pojo which consists of the below members so below is the pojo with few members in it
public class TnvoicetNotify {
private List<TvNotifyContact> toMap = new ArrayList<TvNotifyContact>();
private List<TvNotifyContact> ccMap = new ArrayList<TvNotifyContact>();
}
now in some other class i am getting the object of above class TnvoicetNotify in a method signature as parameter as shown below .. So i want to write the code of extraction from list and storing them in string array within this method itself
public void InvPostPayNotification(TnvoicetNotify TnvoicetNotify)
{
String[] mailTo = it should contain all the contents of list named toMap
String[] mailCC = it should contain all the contents of list named ccMap
}
now in the above class i need to extract the toMap which is of type list in the above pojo named TnvoicetNotify and i want to store each item if arraylist in a string array as shown in below fashion
for example first item in list is A1 and second is A2 and third is A3
so it should be stored in string array as
String[] mailTo = {"A1","A2","A3"};
similarly i want to achieve the same for cc section also as in above pojo it is in list i want to store in the below fashion
String[] mailCc = {"C1","C2","C3"};
so pls advise how to achieve this within InvPostPayNotification method
Pseudo code, because I don't know details for TnvoicetNotify:
public void invPostPayNotification(final TnvoicetNotify tnvoicetNotify)
{
final List<String> mailToList = new ArrayList<>();
for (final TvNotifyContact tv : tnvoicetNotify.getToMap()) { // To replace: getToMap()
mailToList.add(tv.getEmail()); // To replace: getEmail()
}
final String[] mailTo = mailToList.toArray(new String[mailToList.size()])
// same for mailCc then use both arrays
}
If you are using Java 8, you could simply use a one liner :
String[] mailCC = ccMap.stream().map(TvNotifyContact::getEmail).toArray(String[]::new);

Two dimensional string array in java

I am new to java please help me with this issue.
I have a string lets say
adc|def|efg||hij|lmn|opq
now i split this string and store it in an array using
String output[] = stringname.split("||");
now i again need to split that based on '|'
and i need something like
arr[1][]=adc,arr[2][]=def and so on so that i can access each and every element.
something like a 2 dimensional string array.
I heard this could be done using Arraylist, but i am not able to figure it out.
Please help.
Here is your solution except names[0][0]="adc", names[0][1]="def" and so on:
String str = "adc|def|efg||hij|lmn|opq";
String[] obj = str.split("\\|\\|");
int i=0;
String[][] names = new String[obj.length][];
for(String temp:obj){
names[i++]=temp.split("\\|");
}
List<String[]> yourList = Arrays.asList(names);// yourList will be 2D arraylist.
System.out.println(yourList.get(0)[0]); // This will print adc.
System.out.println(yourList.get(0)[1]); // This will print def.
System.out.println(yourList.get(0)[2]); // This will print efg.
// Similarly you can fetch other elements by yourList.get(1)[index]
What you can do is:
String str[]="adc|def|efg||hij|lmn|opq".split("||");
String str2[]=str[0].split("|");
str2 will be containing abc, def , efg
// arrays have toList() method like:
Arrays.asList(any_array);
Can hardly understand your problem...
I guess you may want to use a 2-dimenison ArrayList : ArrayList<ArrayList<String>>
String input = "adc|def|efg||hij|lmn|opq";
ArrayList<ArrayList<String>> res = new ArrayList<ArrayList<String>>();
for(String strs:input.split("||")){
ArrayList<String> strList = new ArrayList<String>();
for(String str:strs.split("|"))
strList.add(str);
res.add(strList);
}

Format an arraylist

I have a file that I am storing into an ArrayList and I can't figure out how to format it so that certain Strings of text are stored in particular indexes. The first line will be the category, second line the question and 3rd the answer to trivia questions. I need to do this so that I can then randomly pick questions then check the answers for a trivia game. All I get so far is every word separated by a comma. From the professor,
"The input file contains questions and answers in different categories. For each category, the first line indicates the name of the category. This line will be followed by a number of pairs of lines. The first line of the pair is the question, and the second line is its corresponding answer.
A blank line separates the categories."
Here is my code so far:
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class TriviaGamePlayer {
/**
* #param args
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
ArrayList<String> triviaQuestion = new ArrayList<String>();
Scanner infile = new Scanner(new File("trivia.txt"));
while(infile.hasNext()){
triviaQuestion.add(infile.next());
}
System.out.println(triviaQuestion);
}
}
From what I can see in the question so far, You would be best off creating your own TriviaQuestion Object which would look something like
public class TriviaQuestion
{
public String question;
public String answer;
public boolean asked;
public String category;
TriviaQuestion (String q, String a, String c)
{
question = q;
answer = a;
category = c;
}
}
Then you have a few options, but if you have this Object then everything becomes a bit easier. I would create a Map<String,List<TriviaQuestion>> where the key is your category.
Then when reading the file, also you should use infile.hasNextLine() and inFile.nextLine()
Read a line (first I assume would be the category)
Read next two lines (question and answer)
Create new instance `new TriviaQuestion( question, answer, category)'
Add this to the Array list
Repeat until blank
If next line is blank, add list to map and loop back to (1)
Like: (this is assuming well formed file)
String line = inFile.nextLine(); //first line
String category = line;
while(infile.hasNextLine())
{
line = inFile.nextLine();
if(line.isEmpty()) //blank line
category = inFile.nextLine();
else
{
String q = line;
String a = inFile.nextLine();
//do other stuff
}
}
Then to ask a question get the list for the category, choose a random question then set it to asked so it doesn't come up again
ArrayList<TriviaQuestion> questions = yourMap.get("Science");
Integer aRandomNumber = 23 //(create a random Number using list size)
TriviaQuestion questionToAsk = questions.get(aRandomNumber)
System.out.println(questionToAsk.question)
questionToAsk.asked = true
I would approach this problem by identifying what is needed. You have a list of categories (Strings). Within each category, there will be a list of question (String) and answer (String) pairs. From there we already see some "logical" ways to organize the data.
Questions - String
Answers - String
Question/Answer pairs - Write a class (for now, lets refer to it as QAPair) with two Strings as fields (one for the question, one for the answer)
List of Q/A pairs within a category - ArrayList
List of Categories, mapped to a list of Q/A pairs - Maybe a Map would do the trick. The type would be: Map>
From there you would start parsing the file; for the first line, or after a blank line is encountered, you know the String will give a category name. You can call containsKey() to check if the category name already exists; if it does fetch the ArrayList of Q/A Pairs for that category and keep adding to the list, otherwise initialize a new ArrayList and add it to the map for that category.
You could then read a pair of lines. For each pair of lines you read initialize a QAPair object, then add it to the ArrayList for the category they belong to.
Here's an example of using a Map:
Map<String, ArrayList<QAPair>> categories = new HashMap<String, ArrayList<QAPair>>();
if (!categories.containsKey("Math")) { // Check to see if a Math category exists
categories.put("Math", new ArrayList<QAPair>()); // If it doesn't, create it
}
QAPair question1 = new QAPair("2+2", "4");
// get() method returns the ArrayList for the "Math" category
// add() method adds the QAPair to the ArrayList for the "Math" category
categories.get("Math").add(question1);
To get the list of categories from a map and pick one:
// Convert to an array of Strings
String[] catArray = categories.toArray(new String[0]);
// Get the 10th category in the array
// Use catArray.length to find how many categories there are total
catArray[10];

Categories