How to split a string in Java? - java

I have a group of radio buttons and a group of checkboxes. I want to print out the selected radio buttons/checked boxes. To print out the radio button selected I use
Object table = radio.getValue();
System.out.println(table);
I get the radio button selected. To get which checkboxes have been selected I use the same:
Object columns = check.getValue();
System.out.println(columns);
I get the checkboxes which have been checked but with square brackets surrounding them, e.g
if I check the boxes
columnA, columnC, columnF
the printed line would look like this:
[columnA, columnC, columnF]
I want to put the strings of the selected checkboxes into my sql query so I have something like this data.executeQuery("Select " + columns + " From " + table);
It works with the table but it doesn't work with the columns.

For this paricular application, you do not need to split a string. You may use
String str = columns.toString(); // "[colummA, colummC, colummF]"
System.out.println(str.substring(1, str.length() - 1));
You may also form a comma-separated string using
StringBuilder sb = new StringBuilder();
for(Object obj : columns) {
if (sb.length() != 0) sb.append(",");
sb.append(obj);
}
However, to answer the question:
String is splitted via split(String) method using a Regular Expression syntax. As you have a list of items, converting it to a String and splitting it isnt an effective decision.

columns is an array containing all values of the selected checkboxes. Make sure that the default toString method outputs the items separated by a ","

this is because default
check.getValue().toString()
called and depending on if its a List or a HashSet and default toString() method of List/HashSet is called which by default appends [] while printing the values so for your case you could either use a collection with a overridden toString() method as per your requirement or just write you custom toString method and call it instead of the default toString Method
here is a sample implementation if it is HashSet
private String getHashSetString(Set<String> myset){
StringBuilder sb = new StringBuilder();
Iterator<String> i = myset.iterator();
if (! i.hasNext())
return "";
for (;;) {
Long e = i.next();
sb.append(e);
if (! i.hasNext())
return sb.toString();
sb.append(",");
}
}
So instead of
data.executeQuery("Select " + columns + " From " + table);
write
data.executeQuery("Select " + columns.getHashSetString() + " From " + table);

Related

Looping through collection

I got a problem with this code:
for (String functionChain : stringCollection) {
lblSource.setText(functionChain);
System.out.print(functionChain);
}
I want to set the text to lblSource as a "chain" of all the collected strings.
It does work with the System.out , i mean it does output as I want but it doesnt Set the Text to the Label, it only sets the LAST valor of the array.
Why is this happening? I mean, the system.out is fine and i am taking same variable "functionChain"... However the output is different in the system.out as in the label.
Get the old value first and concatenate.
lblSource.setText(lblSource.getText() + functionChain);
setText() does what it sounds like it does: it sets the text of the label.
Try this instead:
String s = "";
for (String functionChain : stringCollection) {
s += functionChain;
System.out.print(functionChain);
}
lblSource.setText(s);
lblSource.setText(functionChain) will over write the existing value with new value.
To have all the values of string collection , loop through the string collection , append the values and then set the value to lblSource.
eg :
StringBuilder sb = new StringBuilder();
loop through the collection.
sb.append(each value);
sb.append (",") // a separator if required
then
lblSource.setText(sb.toString())

How to compare strings to get missing word?

I have created a table and some buttons to remove/add rows.
Problem is, when I add a new row, I must insert a value in the field name which isn't already on that table. Let me explain.
Here is the default table:
Now imagine i remove Station 3:
If i add a new Station, I would want to add a new Station name Station 3 (which is missing on the list) but I am adding a new Station 5 (obviously as my code is not correct).
My code for the Add Button action event is as such:
private void jButton10ActionPerformed(java.awt.event.ActionEvent evt) {
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
String s2 = "";
String s1 = "Station 1 Station 2 Station 3 Station 4 Station 5";
int tb1rows = jTable1.getRowCount();
if (tb1rows == 5) {
// ERROR - MAXIMUM STATION NUMBER
}
else {
for (int i=0; i<tb1rows;i++) {
s2.concat(jTable1.getValueAt(i,1).toString());
s2.concat(" ");
}
String[] s3=s2.split(" ");
for (int i=0;i<s3.length;i++) {
if (s1.contains(s3[i])) {
System.err.println("contains");
System.out.println(s3[i]);
}
}
model.insertRow(jTable1.getRowCount(),new Object[] {jTable1.getRowCount() + 1,"Station " + (jTable1.getRowCount()+1),10,false,0,Color.BLACK});
}
}
What's wrong with my logic? Is there a better way to handle the problem so that I can get the "Station x" that is missing in that column so that I can re-add it?
Thanks in advance for your answers.
As there is a space in "Station 1" split on space won't do. Instead using another separator like ";", better use a Set<String> values = new HashSet<String>().
So long as you have
"Station " + (jTable1.getRowCount()+1)
the new station is always going to be named "Station N + 1".
Assuming you fix the problem of splitting on a space described by another answer, your code should be something like
for (int i=0;i<s3.length;i++) {
if (s1.contains(s3[i])) {
System.err.println("contains");
System.out.println(s3[i]);
}
else {
model.insertRow(jTable1.getRowCount(),new Object[] {jTable1.getRowCount() + 1,"Station " + (i + 1) ,10,false,0,Color.BLACK});
}
}
instead of all that string manipulation, you could use set mainpulations:
HashSet<String> all = new HashSet<String>();
// then populate all with your 5 station strings (loop)
HashSet<String> have = new HashSet<String>();
// then populate all with the contents of your table (loop)
all.removeAll(have);
// all now contains the ones that weren't in the table.
if its ordered you can just find the first gap and insert there. so iterate over the rows and if nextrow.numberInIt > thisrow+1 you insert thisrow+1
Code should be something like this:
int nextNrToInsert;
for(int=0; i < tb1rows; i++){
thisrowNr = jTable1.getValueAt(i,1).toString();
NextrowNr = jTable1.getValueAt(i+1,1).toString();
if(nextrowNr > thisrowNr+1){
//found the gap
nextNrToInsert = thisrowNr+1;
break;
}
}
//change this to use nextNrToInsert
model.insertRow(jTable1.getRowCount(),new Object[] {jTable1.getRowCount() + 1,"Station " + (jTable1.getRowCount()+1),10,false,0,Color.BLACK});
This line is the issue
model.insertRow(jTable1.getRowCount(),new Object[] {jTable1.getRowCount() + 1,"Station " + (jTable1.getRowCount()+1),10,false,0,Color.BLACK});
You're always adding in the row with the rowCount() + 1. So even if you remove Station 3, there are 4 rows, and you're adding in row + 1.
This code has no effect:
for (int i=0; i<tb1rows;i++) {
s2.concat(jTable1.getValueAt(i,1).toString());
s2.concat(" ");
}
At loop exit, s2 will still be an empty string, so s3 will be an empty array.
But, the approach to concatenate strings and then split them is misguided, anyway. If all you need is find the lowest integer that, appended to "Station" will produce a unique string, the most natural approach is to make your own TableModel that uses a list of your own objects for each row's data. In that data you'll keep the integer itself, and not the entire string "Station n". Then it's going to be a trivial matter to find a hole in the list of integers.

Java - remove strings from an ArrayList that contains the specified

Sometimes, due to faulty data collected, a line generated by the following method ends up looking like this when saved: ",-1,0" or something similar, with no name, an ID of -1 and a level of 115 or something else. (The lines are formatted like this (excluding quotes): "name,id,level" (e.g: "Honour guard,5514,115")
What i need to do is to remove all strings in monstersToAdd that contains -1.
I've tried this, but with no success:
private void combineInfo() {
for(int i = 0; i < monsterList.size(); i++){
monstersToAdd.add("" + names[i] + "," + IDs[i] + "," + levels[i]);
}
monstersToAdd.remove(monstersToAdd.contains("-1"));
}
with the line monstersToAdd.remove(monstersToAdd.contains("-1")); I was trying to remove all strings in monstersToAdd that contains "-1". This however does not work, probably for good reasons, which I unfortunately don't know of yet.
I would really appreciate any input :).
You would be better off not adding the lines you don't want in the first place.
for (....) {
if (IDs[i] != -1) {
// add it
}
// else it simply doesn't get added
}
More on your original code: You could post a little more detail, such as the type of monsterToAdd. If it is a non-generic list, then the contains method just returns true or false depending if the parameter (here a string of "-1") is present in the list exactly as you pass it, that is it doesn't search for substring matches of the list elements.
remove then tries to remove the element you ask to remove, which may be a Boolean object, automatically boxed from the boolean primitive value returned by contains.
Also, it is suspicious that you have a variable called monsterList which you use for iteration length, but not actually use any elements from that list. Maybe the arrays you use have the same values as the list, and were copied out beforehand? If so, it would be nicer to iterate on the monsterList directly and use its elements.
Its easier if you dont even add them, than adding and removing them so check the sanity of ID names and levels before adding them
private void combineInfo() {
for(int i = 0; i < monsterList.size(); i++){
//add only if name is non empty, ID is not negative and level is below 100
if(!(names[i].isEmpty() || IDs[i]<0 || levels[i]>100))
monstersToAdd.add("" + names[i] + "," + IDs[i] + "," + levels[i]);
}
Why don't you do this instead:
private void combineInfo() {
for(int i = 0; i < monsterList.size(); i++){
if(IDs[i] != -1){
monstersToAdd.add("" + names[i] + "," + IDs[i] + "," + levels[i]);
}
}
monstersToAdd.remove(monstersToAdd.contains("-1"));
}
That way, you never add the monster to the list in the first place, if the ID is -1.
You are really close:
private void combineInfo() {
for(int i = 0; i < monsterList.size(); i++){
if (IDs[i] == -1) continue; // Skip this iteration
monstersToAdd.add("" + names[i] + "," + IDs[i] + "," + levels[i]);
}
}
Filter them out as early as possible rather than back-tracking and removing them.
contains() returns only a true/false result depending on whether the list contains the given input object (in your case the string "-1"). So in your example, your list wouldn't contain "-1", so your remove statement would be resolved to this:
monstersToAdd.remove(false);
which wouldn't work for obvious reasons.
Here is the code:
for(Iterator<String> it = monsterList; it.hasNext();) {
String elem = it.next();
if (elem.contains("-1")) {
it.remove();
}
}
contains() method of collection returns true if collection contains element equals to one passed as an argument. In you case you want to use String's contains() that returns true if the string contains specified substring. This is the reason that you need loop.
This loop must be implemented with iterator. Using new java 5 syntax for(String elem : list) will not work here because you have to remove element. Using for(int i = 0; i < list.size(); i++) requires implementation of logic that safely moves to the next index after element removal.
And the last point. You have to use iterator.remove() instead of Collection.remove() to avoid ConcurrentModificationException

Using JOptionPane

if i was using a JOptionPane message dialog box how would I be able to show an the whole array in the message section such as this little snipit? or would that evenbe possible?
public void showTheMessage()
{
JOptionPane.showMessageDialog(null,"These are are all the colors to
choosfrom,\n"+ arrayOfcolors[the whole array], "Color box");
}
The easiest thing to do would be to concatenate all the elements of the array into one big string.
String colors = "";
for(int i = 0; i < arrayOfColors.length; i++)
colors += arrayOfColors[i] + " ";
The showOptionDialog method lets the user select a single element from an array of options, which I think is what you're looking for.
In case its an array of Color objects
String colors="";
for (Color c: arrayOfColors)
colors+= c.toString() + " ";
Otherwise if its an array of String objects
String colors="";
for (String s: arrayOfColors)
colors+= s + " ";
Just a note, using StringBuilder is much faster, but this is just a small array i guess.

How to display an array to the user

I'm trying to display the contents of an ordered array in something like a JTextField.
for (int i=0; i<array.length; i++) {
this.textField.setText(array[i]);
}
This won't work for two reasons. The first minor reason: if the array length is 4 then jtextfield is getting it's value reset 4 times rather than appending each element onto the last.
Second reason: The JTextField only takes strings. I can't find anything I can use in Swing that will let me display integers to the user. Any help?
Quick & Dirty Answer
for (int i=0; i<array.length; i++) {
this.myJTextField.setText(this.myJTextField.getText() + ", " + array[i]);
}
Correct Way
First, calling a member variable JTextField probably isn't wise. Since the class is already called like that, it will confuse readers. Naming conventions in Java state member variables are like myTextField for example. (note: original question changed).
User defined format
Note you can convert any number to a string by simply doing "" + number too. If you have many strings, consider using a string builder, as that's faster and won't update the GUI element multiple times: (also fixes the initial ", " before the first item, which happens above)
StringBuilder builder = new StringBuilder();
for (int i=0; i<array.length; i++) {
builder.append(array[i]));
if(i + 1 != array.length)
builder.append(", ");
}
this.myJTextField.setText(builder.toString());
Canonical array representation
Alternatively, you can use this:
this.myJTextField.setText(Arrays.toString(array));
It will look like [1, 4, 5, 6].
You can concatenate all those integers into a string the then present that value in the textfield.
StringBuilder sb = new StringBuilder();
for( int i : array ) { // <-- alternative way to iterate the array
sb.append( i );
sb.append( ", " );
}
sb.delete(sb.length()-2, sb.length()-1); // trim the extra ","
textField.setText( sb.toString() );
You can use a JTextArea instead of the textfield too.

Categories

Resources