arraylist loop not displaying - java

I need to make a program that let's you add CD titles, remove them etc.
I need to use an Arraylist for my program (to store the songs)
Code:
ArrayList songlist = new ArrayList();
Collections.addAll(songlist, "Something", "Hard Days Night", "I am the Walrus", "Yesterday", "All the Lonely People");
Collections.sort(songlist);
int songlistsize = songlist.size ();
for (int i = 0; i < songlistsize; i++) {
outputField.setText(i + ": " + songlist.get(i));
The problem is that the program will only display "Yesterday", and not anything else.

outputField.setText(i + ": " + songlist.get(i));
Because you are setting the last value and not appending. Do something like this:
StringBuilder string = new StringBuilder();
for (int i = 0; i < songlistsize; i++) {
string.append(songlist.get(i));
}
outputField.setText(string);
There are many other problems with the code but I am sticking to the point.

If you try to print your output on the console you will see that the part that deals with the collection works fine.
But since setText() replaces the current String with the latest song name you only see "Yesterday" because its at the end of your collection.
That´s why you should try to append() the next song name to your String or make sure you copy your current String, add the next item and finally use setText()
For example:
String string = "";
for (int i = 0; i < songlistsize; i++)
{
string = outputField.getText() + songlist.get(i);
outputField.setText(string);
}

Related

Retreiving values from HashMap<String, String> for each character of a string returns NULL

I'm learning Java and as a project I'm trying to make a program that uses a HashMap to accept a string from the user then return the corresponding (pseudo-Pinyin) values as a quasi-encrypted String.
I got this to work when the String was just 1 character in length, but my many attempts to handle full sentence failed.
In a prior SO Question, this was marked as duplicate (and I deleted the question), but the prior related solution:
for (int i = 0; i < args.length(); i++){
char c = args.charAt(i);
s += lookup.get(c);
s += " ";
}
Actually doesn't solve my problem.
The best result I've been able to get using the for loop indicated as a previously posted solution was to return a string that prints null for every character entered by the user. For example, hello becomes null null null null null.
Here's the relevant part of the code (Encrypt2Pinyin.java):
package pinyincrypto;
import java.util.*;
public class Encrypt2Pinyin {
public static String e2p(String args){
HashMap<String, String> lookup = new HashMap<>();
lookup.put("a", "xuduo");
lookup.put("b", "bai");
lookup.put("c", "cai");
lookup.put("d", "dai");
lookup.put("e", "tao");
lookup.put("f", "nao");
lookup.put("g", "lao");
lookup.put("h", "zheng");
lookup.put("i", "ceng");
lookup.put("j", "sheng");
lookup.put("k", "peng");
lookup.put("l", "che");
lookup.put("m", "shui");
lookup.put("n", "ge");
lookup.put("o", "zhi");
lookup.put("p", "nu");
lookup.put("q", "ren");
lookup.put("r", "nan");
lookup.put("s", "hai");
lookup.put("t", "xihuan");
lookup.put("u", "wo");
lookup.put("v", "wu");
lookup.put("w", "chi");
lookup.put("x", "niu");
lookup.put("y", "duo");
lookup.put("z", "yunxing");
lookup.put("A", "Xuduo");
lookup.put("B", "Bai");
lookup.put("C", "Cai");
lookup.put("D", "Dai");
lookup.put("E", "Tao");
lookup.put("F", "Nao");
lookup.put("G", "Lao");
lookup.put("H", "Zheng");
lookup.put("I", "Ceng");
lookup.put("J", "Sheng");
lookup.put("K", "Peng");
lookup.put("L", "Che");
lookup.put("M", "Shui");
lookup.put("N", "Ge");
lookup.put("O", "Zhi");
lookup.put("P", "Nu");
lookup.put("Q", "Ren");
lookup.put("R", "Nan");
lookup.put("S", "Hai");
lookup.put("T", "Xihuan");
lookup.put("U", "Wo");
lookup.put("V", "Wu");
lookup.put("W", "Chi");
lookup.put("X", "Niu");
lookup.put("Y", "Duo");
lookup.put("Z", "Yunxing");
lookup.put(" ", " ");
lookup.put(".", "?");
lookup.put("!", ".");
lookup.put("?", "!");
lookup.put("$", "%");
lookup.put("%", "$");
lookup.put("#", "&");
lookup.put("&", "#");
lookup.put("#", "*");
lookup.put("*", "#");
lookup.put("^", "]");
lookup.put("(", ")");
lookup.put(")", "(");
lookup.put("-", "-");
lookup.put("=", "+");
lookup.put("+", "=");
lookup.put("\n", "\n");
lookup.put(" ", " ");
//Vector vec = new Vector();
//vec.add(args);
//Iterator<HashMap<K, V>> itr = lookup.values().iterator();
//String[] vec = args;
//Vector<String> vector = null;
//while (itr.hasNext())
//{
//vector=(vec)itr.next();
// }
//String[] str = null;
//s = args.split("(?!^)") ;
String s = " ";
//String str = args.trim();
for (int i = 0; i < args.length(); i++){
char c = args.charAt(i);
s += lookup.get(c);
s += " ";
}
//return(lookup.get(args.charAt(1))); // just a test -- still returns null
return(s);
}
}
If it's useful I can also provide the corresponding code for the .java file containing my main function.
If your map has String as key, you cannot use a char
char c = args.charAt(i);
s += lookup.get(c); // you are giving char as key, what is not valid!!!
Use this workaround:
for (int i = 0; i < args.length(); i++){
char c = args.charAt(i);
s += lookup.get(c+"");
// ↑ ugly but converts char to String
s += " ";
}
Or this one, more polite:
for (int i = 0; i < args.length(); i++){
String c = Character.toString(args.charAt(i));
s += lookup.get(c);
s += " ";
}
It is returning null because you have declared your map as HashMap<String, String> lookup with String as the type for your key and then you are trying to retrieve using a char
char c = args.charAt(i);
s += lookup.get(c);
which is why it is returning null.
So use this instead :
char c = args.charAt(i);
s += lookup.get(new String(c));
The problem with your approach is that the keys in the map are of type String, while the keys that you are using for the lookup are of type char.
You can solve it in two ways:
Convert the char to String - for example, by concatenating it with "", calling toString, or using valueOf method, or
Changing the map to HashMap<Character,String>.
The first approach (converting char to String is slightly more wasteful, because it makes lots of throw-away one-character strings. Although accessing by char requires boxing, Character class interns all the characters that your code is using, and reuses the same object for its boxing conversion. This eliminates the waste.
The second approach is a lot cleaner, and it would let you keep the lookups unchanged. All you need to change is the insertions:
Map<Character,String> lookup = new HashMap<>();
lookup.put('a', "xuduo");
lookup.put('b', "bai");
lookup.put('c', "cai");
...
Everything else would continue to work without additional changes.

Having trouble with string concatenation

I was trying to concatenate a string to itself + something else, like this:
String example = " "
for (int i = 0; i < 5; i++) {
if (condition OK) {
example = example + "\nAnother text";
}
}
JOptionPane.showMessageDialog(null, example);
In my mind, it should've print " (new line)Another text" but it seems to work only with the last entry in my "Another text". Like, if the condition inside the "for" loop is OK 3 times, it prints " (new line)Another text(3)" instead of " (new line) Another Text(1) (new line) Another text(2)...
Any idea of what may be happening?
EDIT: after realizing that my code was fine, I followed afzalex recommendation and found out the error was in my condition. Thanks bro
I used below program I got expected output.
String example = " ";
for (int i = 0; i < 5; i++) {
if (i == 1 || i == 3) {
example = example + "\nAnother text";
}
}
System.out.println(example);
Output:
Another text
Another text
So, probably it could be something wrong with JOptionPane.showMessageDialog(null, example); If it is being interpreted as HTML in the end, then better use </br> instead of \n, that can give you new line.

Junk characters "&#7;" are added and stopping application tool tip functionality to work

Tool tip- functionality is working fine for 1 object but when more object get add at that time it fails.
In catalina.out objects are displayed with no junk characters but when I look in UI via f12, I can see junk character "&#7;".
In java code I used replaceAll and split but no success.
Code-
sHasCP1+="ISS-0000430&#7;ISS-0000434&#7;ISS-0000435&#7;ISS-0000436";
//sHasCP1 = sHasCP1.replace("&#7;" , ";");
//sHasCP1 = sHasCP1.replace("[^a-zA-Z0-9]" , " ");
String[] seperator = new String[50];
seperator = sHasCP1.split("&#7;");
List<String> list = (List) Arrays.asList(seperator);
StringBuilder name = new StringBuilder();
//display elements of List
System.out.println("String array converted to List");
for(int i=0; i < list.size(); i++){
name.append(list.get(i));
if ( i != list.size()-1){
name.append(", ");
}
System.out.println(name.toString());
}
and I am passing name value in title -
sbOut.append("<img src=\"..conCP.gif\" border=\"0\" title=\""+name+ "\"/>");
Not knowing where and when the HTML entity is introduced; the following should do:
final String REPLACEMENT = "\t"; // Or ""?
sHasCP1 = sHasCP1.replace("&#7;", REPLACEMENT);
sHasCP1 = sHasCP1.replace("", REPLACEMENT);
sHasCP1 = sHasCP1.replace("\u0007", REPLACEMENT);
In a first version I leave a TAB character instead. ", " or so would do too.
Nicer would be to inspect/debug/log the exact string.

How to store stringbuffer into string array?

Hi i am reading sqlite db data and store into string buffer. I want to display it in the list view in android. i am facing little problem. please help me to solve this issue.
String studentno=cursor.getString(1);
String date=cursor.getString(2);
buffer.append("student: "+studentno+" Time:"+date+"\n");
String data=buffer.toString();
Log.d("student: "+studentno+" Time:"+date);
the output is:student: 1234 Time:12:13
student: 1234 Time:12:14
student: 1234 Time:12:15
I want to store string buffer like this
values[0]=student: 1234 Time:12:13
values[1]=student: 1234 Time:12:14
values[2]=student: 1234 Time:12:15
i tried below coding but its not working.
String[] values = data.split("");
for (int i = 0; i < values.length; ++i) {
list.add(values[i]);
}
is there any way to do this. thanks in advance.
You seem to be adding the data into the buffer with new line delimiter at the end. Splitting them should look like this: data.split("\n");
This does not seem like a good idea, however. Mainly because you can have a very large data set and split is an expensive operation.
Why not create an ArrayList<String> and call list.add("student: " + studentno + " Time: " + date) or some other more efficient structure?
Code:
List<String> list = new ArrayList<String>();
String studentno=cursor.getString(1);
String date=cursor.getString(2);
list.add("student: " + studentno + " Time: " + date);
This makes no sense. If you want to store the data in an array, don't store it in a StringBuffer in the first place. Store it directly in the array.
You must have some loop in which you read the data :
String[] arr = new String [...];
int count = 0;
while (cursor.next() && count < arr.length) {
String studentno=cursor.getString(1);
String date=cursor.getString(2);
arr[count] = "student: "+studentno+" Time:"+date+"\n";
count++;
}
You could try to replace your split call with this:
String[] values = data.split("\n");

Trim() in Java not working the way I expect? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Query about the trim() method in Java
I am parsing a site's usernames and other information, and each one has a bunch of spaces after it (but spaces in between the words).
For example: "Bob the Builder " or "Sam the welder ". The numbers of spaces vary from name to name. I figured I'd just use .trim(), since I've used this before.
However, it's giving me trouble. My code looks like this:
for (int i = 0; i < splitSource3.size(); i++) {
splitSource3.set(i, splitSource3.get(i).trim());
}
The result is just the same; no spaces are removed at the end.
Thank you in advance for your excellent answers!
UPDATE:
The full code is a bit more complicated, since there are HTML tags that are parsed out first. It goes exactly like this:
for (String s : splitSource2) {
if (s.length() > "<td class=\"dddefault\">".length() && s.substring(0, "<td class=\"dddefault\">".length()).equals("<td class=\"dddefault\">")) {
splitSource3.add(s.substring("<td class=\"dddefault\">".length()));
}
}
System.out.println("\n");
for (int i = 0; i < splitSource3.size(); i++) {
splitSource3.set(i, splitSource3.get(i).substring(0, splitSource3.get(i).length() - 5));
splitSource3.set(i, splitSource3.get(i).trim());
System.out.println(i + ": " + splitSource3.get(i));
}
}
UPDATE:
Calm down. I never said the fault lay with Java, and I never said it was a bug or broken or anything. I simply said I was having trouble with it and posted my code for you to collaborate on and help solve my issue. Note the phrase "my issue" and not "java's issue". I have actually had the code printing out
System.out.println(i + ": " + splitSource3.get(i) + "*");
in a for each loop afterward.
This is how I knew I had a problem.
By the way, the problem has still not been fixed.
UPDATE:
Sample output (minus single quotes):
'0: Olin D. Kirkland                                          '
'1: Sophomore                                          '
'2: Someplace, Virginia  12345<br />VA SomeCity<br />'
'3: Undergraduate                                          '
EDIT the OP rephrased his question at Query about the trim() method in Java, where the issue was found to be Unicode whitespace characters which are not matched by String.trim().
It just occurred to me that I used to have this sort of issue when I worked on a screen-scraping project. The key is that sometimes the downloaded HTML sources contain non-printable characters which are non-whitespace characters too. These are very difficult to copy-paste to a browser. I assume that this could happened to you.
If my assumption is correct then you've got two choices:
Use a binary reader and figure out what those characters are - and delete them with String.replace(); E.g.:
private static void cutCharacters(String fromHtml) {
String result = fromHtml;
char[] problematicCharacters = {'\000', '\001', '\003'}; //this could be a private static final constant too
for (char ch : problematicCharacters) {
result = result.replace(ch, ""); //I know, it's dirty to modify an input parameter. But it will do as an example
}
return result;
}
If you find some sort of reoccurring pattern in the HTML to be parsed then you can use regexes and substrings to cut the unwanted parts. E.g.:
private String getImportantParts(String fromHtml) {
Pattern p = Pattern.compile("(\\w*\\s*)"); //this could be a private static final constant as well.
Matcher m = p.matcher(fromHtml);
StringBuilder buff = new StringBuilder();
while (m.find()) {
buff.append(m.group(1));
}
return buff.toString().trim();
}
Works without a problem for me.
Here your code a bit refactored and (maybe) better readable:
final String openingTag = "<td class=\"dddefault\">";
final String closingTag = "</td>";
List<String> splitSource2 = new ArrayList<String>();
splitSource2.add(openingTag + "Bob the Builder " + closingTag);
splitSource2.add(openingTag + "Sam the welder " + closingTag);
for (String string : splitSource2) {
System.out.println("|" + string + "|");
}
List<String> splitSource3 = new ArrayList<String>();
for (String s : splitSource2) {
if (s.length() > openingTag.length() && s.startsWith(openingTag)) {
String nameWithoutOpeningTag = s.substring(openingTag.length());
splitSource3.add(nameWithoutOpeningTag);
}
}
System.out.println("\n");
for (int i = 0; i < splitSource3.size(); i++) {
String name = splitSource3.get(i);
int closingTagBegin = splitSource3.get(i).length() - closingTag.length();
String nameWithoutClosingTag = name.substring(0, closingTagBegin);
String nameTrimmed = nameWithoutClosingTag.trim();
splitSource3.set(i, nameTrimmed);
System.out.println("|" + splitSource3.get(i) + "|");
}
I know that's not a real answer, but i cannot post comments and this code as a comment wouldn't fit, so I made it an answer, so that Olin Kirkland can check his code.

Categories

Resources