Looping through collection - java

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())

Related

How to remove extra spaces from arraylist

I have to retrieve values from database and add it into arraylist .Here is my code ..
ArrayList country = new ArrayList();
strQuery = "Select * from country";
rs = conexiondb.Consulta(strQuery);
while (rs.next()) {
String toc = rs.getString("country");
country.add(toc);
}
out.print(country);
System.out.println(country);
out.close();
i have added all the values retrieved from database into country..and here is the values present in the country..
[APAC, North America, South America, Europe]
Now as per my need i have to remove space after each comma values and make it like this..
[APAC,North America,South America,Europe]
Please guys help me to solve this..
Thanks in advance.
What you are seeing is how ArrayList formats it's contents, not the results of your query, try something like...
for (String name : country) {
System.out.println("[" + name + "]");
}
To check. If there are still spaces in the output, then you can use String#trim when you extract the values from the database and before you place them in the List
If you need to format the String, you need to provide you own mechanism, for example...
List<String> values = new ArrayList<>();
values.add("APAC");
values.add("North America");
values.add("South America");
values.add("Europe");
System.out.println(values);
StringBuilder sb = new StringBuilder(128);
for (String value : values) {
if (sb.length() > 0) {
sb.append(",");
}
sb.append(value);
}
sb.insert(0, "[");
sb.append("]");
System.out.println(sb);
Which outputs...
[APAC, North America, South America, Europe]
[APAC,North America,South America,Europe]
You are relying on the default formatting provided by ArrayList.toString(). Don't do that. Write your own formatting code.
The spaces aren't coming from the database at all, they are just a function of the way ArrayList.toString() (and in fact all of the JDK Collection classes which inherit from AbstractCollection) pretty prints your list.
You can tell this is the case either by looking at the documentation for this class, or by noting that there is no space before the initial [.
I recommend Guava Joiner for full control over your output.
Joiner.on(',').join(country);
will give the String you want.
ArrayList toString method prints the collection using a space after each comma. If you want to print the list without spaces, then you need to write a new method to do that.
If memory is not the issue. store it in a separate StringBuilder
This should not be a difficult problem. It is just a bit of manupluation.
In case you want comma separated value to have space storing in arraylist will give you that.
If you need the result to start and end with square braces with inside values being comma separated without any space in between the strings.
ArrayList <String> country = new ArrayList<String>();
ArrayList country = new ArrayList();
strQuery = "Select * from country";
rs = conexiondb.Consulta(strQuery);
StringBuilder commaSeparated = new StringBuilder("[");
while (rs.next()) {
String toc = (rs.getString("country")).trim();
commaSeparated.append(toc).append(",");
country.add(toc);
}
commaSeparated.append("]");
out.print(country);
System.out.println(country);
System.out.println(commaSeparated.toString());
out.close();

Not Displaying Array List properly?

I only have one arrayList and I want the out put to print in table format I know with Arrays you would need to use a nested for loop one for the rows and the other for the columns, How would I be able to have my output be in a table format when using arrayList my for loop:
System.out.print("Inv/Mo.\tRate\tYears\tFuture Value\n");
for (int i = 0; i < FutureValueArrayList.size(); i++)
{
String FutureValueArray = FutureValueArrayList.get(i);
System.out.print(FutureValueArray + "\t");
}
my for loop gives me an output like this:
$100.00 2.0% 2 $2,450.64 $150.00 2.0% 2 $36,420.71
The bold values are a second entry by the user. How do I get it to display on the second line and for every new entry of values it outputs it line by line as opposed to everything in one line? I tried print/println and it still out puts everything in the first line.
Use Guava library where is Joiner.on(" ").join(arraylist); it produces nicely formatted output, you can define even custom iterators or filters in guava.
https://code.google.com/p/guava-libraries/wiki/StringsExplained#Joiner
To format output better you can use stringObject.replace(x,y); which allows you to replace symbols by e.g. \n - new line or you can add more spaces ...
String str = sentence.replace("and", " ");

How to split a string in 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);

Checking the end of a string in Java multiple times?

So in Java, I know that str.endsWith(suffix) tests if str ends with something. Let's say I have a text with the line "You are old" in it. How would I take the "old" and set it as a variable so I can print it out in the console?
I know I could do:
if(str.endsWith("old")){
String age = "old";
}
But then I'm going to have more options, so then I'd have to do:
if(str.endsWith("option1")){
String age = "option1";
}
if(str.endsWith("option2")){
String age = "option2";
}
...
Is there a more efficient and less verbose way to check the end of strings over writing many, possibly hundreds, of if statements
Format:
setting: option
setting2: option2
setting3: option3 ...
Regardless of what "option" is, I want to set it to a variable.
If you are working with sentences and you want to get the word, do
String word = str.substring(str.lastIndexOf(" "));
You may need a +1 after the lastIndexOf() to leave the space out.
Is that what you are looking for?
Open your file and read the line with the readLine() method. Then to get the last word of the string you can do as it is suggested here
You mean like:
String phrase = "old";
if(str.endsWith(old)){
Is this what you're looking for?
List<String> suffixes = new ArrayList<String>();
suffixes.add("old");
suffixes.add("young");
for(String s: suffixes)
{
if (str.endsWith(s))
{
String age = s;
// .... more of your code here...
}
}
If you're worried about repeating very similar code, the answer is always (99%) to create a function,
So in your case, you could do the following:
public void myNewFunction(String this, String that){
if(this.endsWith(that)){
String this = that;
}
}
...
String str = "age: old";
myNewFunction(str, "old"); //Will change str
myNewFunction(str, "new"); //Will NOT change str
And if that is too much, you can create a class which will do all of this for you. Inside the class, you can keep track of a list of keywords. Then, create a method which will compare a given word with each keyword. That way, you can call the same function on a number of strings, with no additional parameters.
You could use this Java code to solve your problem:
String suffix = "old";
if(str.endsWith(suffix)) {
System.out.println(suffix);
}

strange problem in an array

I'm working on a little server app with Java. So, I'm getting informations from different client, and if information comes in, the following method is called:
public void writeToArray(String data) {
data = trim(data);
String[] netInput = new String[5];
netInput[0]="a";
netInput[1]="a";
netInput[2]="a";
netInput[3]="a";
netInput[4]="a";
netInput = split(data, ",");
pos_arr = PApplet.parseInt(netInput[0]);
rohr_value = PApplet.parseInt(netInput[1]); // THIS LINE KICKS OUT THE ERROR.
if(pos_arr >0 && pos_arr<100) {
fernrohre[pos_arr] = rohr_value;
println("pos arr length: " + fernrohre[pos_arr]);
println("pos arr: " + pos_arr);
}
The console on OS X gives me the following error:
Exception in thread "Animation Thread"
java.lang.ArrayIndexOutOfBoundsException:1
at server_app.writeToArray(server_app.java:108) at server_app.draw(server_app.java:97)
at processing.core.PApplet.handleDraw(PApplet.java:1606)
at processing.core.PApplet.run(PApplet.java:1503)
at java.lang.Thread.run(Thread.java:637)
As you can see, I tried to fill the array netInput with at least 5 entries, so there can't be an ArrayIndexOutOfBoundsException.
I don't understand that, and I'm thankful for your help!
It would work already for me, if I can catch the error and keep the app continuing.
You put 5 Strings into the array, but then undo all your good work with this line;
netInput = split(data, ",");
data obviously doesn't have any commas in it.
In this line
netInput = split(data, ",");
your array is being reinitialized. Your split method probably returns an array with only 1 element (I can guess that data string doesn't contain any ",").
Update
The split() method is custom, not String.split. It too needs to be checked to see what is going wrong. Thanks #Carlos for pointing it out.
Original Answer
Consider this line:
netInput = split(data, ",");
This will split the data string using comma as a separator. It will return an array of (number of commas + 1) resulting elements. If your string has no commas, you'll get a single element array.
Apparently your input string doesn't have any commas. This will result in a single element array (first element aka index = 0 will be the string itself). Consequently when you try to index the 2nd element (index = 1) it raises an exception.
You need some defensive code,
if(netInput.length > 1)
pos_arr = PApplet.parseInt(netInput[0]);
rohr_value = PApplet.parseInt(netInput[1]);
You make
netInput = split(data, ",");
and
split(data, ",");
returns one element array
You are re-assigning your netInput variable when the split() method is called.
The new value might not have an array count of 5.
Can you provide the source for the split() method?

Categories

Resources