Formatting Strings and String arrays with tabs in java - java

I have an assignment where I'm supposed to have a method that formats an array of String objects to be tabulated a certain way with a header, and put all the objects (after being formatted) nicely into a single String for the method to return. This method is inside an object class, so it ultimately will be formatting multiple objects the same way, so I need it to format the same way with various String lengths.
Here's what I need the output to look like:
Hashtags:
#firstHashtag
#secondHashtag
Each hashtag is in a String[] of hashtags,
i.e.
String[] hashtags = ["#firstHashtag", "#secondHashtag"]
So basically I need to use string.format() to create on single string containing a tabbed "Hashtags:" header, and then each String in the "hashtags" array to be on a new line, and double-tabbed. The size of the "hashtag" array changes since it is in an object class.
Could someone help me use String.formatter?
This is what my method looks like so far:
public String getHashtags()
{
String returnString = "Hashtags:";
String add;
int count = 0;
while(count < hashtags.length)
{
//hashtags is an array of String objects with an unknown size
returnString += "\n";
add = String.format("%-25s", hashtags[count]);
//here I'm trying to use .format, but it doesn't tabulate, and I
//don't understand how to make it tabulate!!
count++;
returnString = returnString + add;
}
if(hashtags == null)
{
returnString = null;
}
return returnString;
}
Any helpful advice on what to do here with formatting would be greatly appreciated!!!

If you are trying to use real tabs and not spaces, then just change your program to be like this one:
public String getHashtags()
{
if(hashtags == null)
{
return null;
}
String returnString = "Hashtags:";
int count = 0;
while(count < hashtags.length)
{
//hashtags is an array of String objects with an unknown size
returnString = returnString + "\n\t\t"+hashtags[count];
count++;
}
return returnString;
}

Your String.format() statement will create a String that is left-justified and padded to 25 spaces. For example, this line:
System.out.println("left-justified >" + String.format("%-25s", "hello") + "<");
outputs:
left-justified >hello <
The other thing is that you're not really using tabs (I don't see the tab character in your program). String.format() is creating Strings that are length 25 and left-justified. Keep that in mind as you create the return string. Also, your loop as adding a newline character each time. That's why you're getting multi-line output.

Related

Problem handling multiple substrings on dynamic string

Currently I am having a hard time trying to figure out if there is a better way to refactor the following code.
Given the following:
String detail = "POTATORANDOMFOOD";
Lets say I want to assign variables with different parts of detail, the end result would look something like this.
String title = detail.substring(0, 6); // POTATO
String label = detail.substring(6, 12); // RANDOM
String tag = detail.substring(12, 16); // FOOD
Now lets say the string detail length constantly changes, sometimes it only contains "POTATORANDOM" and no "FOOD", sometimes it contains even more characters "POTATORANDOMFOODTODAY", so another variable would be used.
String title = detail.substring(0, 6); // POTATO
String label = detail.substring(6, 12); // RANDOM
String tag = detail.substring(12, 16); // FOOD
...
String etc = detail.substring(30, 40); // etc value from detail string
The issue with this, is that since the string sometimes is shorter or longer, we would run into the StringIndexOutOfBoundsException which is not good.
So currently I have a naive way to handle this:
if (detail != null || !detail.isEmpty()) {
if (detail.length() >= 6) {
title = detail.substring(0, 6);
if (detail.length() >= 12) {
label = detail.substring(6, 12);
if (detail.length() >= 16) {
tag = detail.substring(12, 16);
.
.
.
}
}
}
}
This can get really messy, especially if lets say the string were to grow even more.
So my question is, what would be a good design pattern that would fit for this type of problem? I have tried the chain of responsibility design pattern but, the issue with this one is that it only returns a single value, while I am trying to return multiple ones if possible. This way I can assign multiple variables depending on the length of the string.
Any help/hints is greatly appreciated!
Edited:
The order and length are always the same. So title will always be first and it will always contain 6 characters. label will always be second and it will always contain 6 characters. tag will always be third and it will always contain 4 characters, etc.
If I was you, I would do the following:
Define a class to hold a Word definition
public class Word {
private final String name;
private final int startIndex;
private final int endIndex;
public Word(String name, int startIndex, int endIndex) {
this.name = name;
this.startIndex = startIndex;
this.endIndex = endIndex;
}
public String getName() { return name; }
public int getStartIndex() { return startIndex; }
public int getEndIndex() { return endIndex; }
}
Create a static list which holds all the possible words
public static final List<Word> WORDS = List.of(
new Word("title", 0, 6),
new Word("label", 6, 12),
new Word("tag", 12, 16),
...
);
Create a function that parses the String detail by walking this list until when the size of the string is exhausted
... and of course storing the elements into a Map<String, String> so that you can access them later.
public Map<String, String> parseDetail(String detail) {
Map<String, String> receivedWords = new LinkedHashMap<>(); //<-- map respecting insertion order
if (detail.isEmpty()) {
return receivedWords;
}
int parsedLength = 0; ​
​for (Word word : WORDS) {
​receivedWords.put(word.getName(), detail.substring(word.getStartIndex(), word.getEndIndex()); //<-- store the current word
parsedLength += word.getEndIndex() - word.getStartIndex(); //increase the parsedLength by the length of your word
if (parsedLength >= detail.length()) {
break; //<-- exit the loop when you're done with the parsing
}
​}
return receivedWords;
}
To sum up:
Map<String, String> receivedWords = parseDetail(detail);
receivedWords.forEach((k, v) -> {
System.out.println("Key: " + k + ", value: " + v);
});
Output:
Key: title, value: POTATO
Key: label, value: RANDOM
Key: tag, value: FOOD
...
Tip 1: The input you receive looks pretty weird. I understand that you cannot change it but I would try to negotiate with the caller (if possible) a better way to send you their input (ideally a structured object, if not possible at least a string with some separator so that you can simply split by that character).
Tip 2: I have defined the list of words statically in the code. But I would instead define an external file (e.g. a Json file, or an Xml, or even a simple text file) that you parse dynamically to create the list. That will allow someone else to configure this file with the words/start index/end index without you having to do it in the code each time there is a change. ​
You could simply check the length of the total string to see if it has the RANDOM and the FOOD attributes before using substring()
String title = "", label = "", tag = "";
if (detail.length() >= 6)
title = detail.substring(0, 6);
if (detail.length() >= 12)
label = detail.substring(6, 12);
if (detail.length() == 16)
tag = detail.substring(12,16);
I would suggest a regex aproach:
public static void main(String[] args) {
String detail = "POTATORANDOMFOODTODAY";
Pattern p = Pattern.compile("(.{0,6})(.{0,6})(.{0,4})(.{0,5})");
Matcher m = p.matcher(detail);
m.find();
String title = m.group(1);
String label = m.group(2);
String tag = m.group(3);
String day = m.group(4);
System.out.println("title: " + title + ", lable: " + label + ", tag: " + tag + ", day: " + day);
}
//output: title: POTATO, lable: RANDOM, tag: FOOD, day: TODAY
If you have a lots of groups I would suggest to use named captured groups. The approach above can particularly be difficult to maintain as adding or removing a group in the middle of the regex upsets the previous numbering used via Matcher#group(int groupNumber). Using named capturing groups:
public static void main(String[] args) {
String detail = "POTATORANDOMFOODTODAY";
Pattern p = Pattern.compile("(?<title>.{0,6})(?<label>.{0,6})(?<tag>.{0,4})(?<day>.{0,5})");
Matcher m = p.matcher(detail);
m.find();
String title = m.group("title");
String label = m.group("label");
String tag = m.group("tag");
String day = m.group("day");
System.out.println("title: " + title + ", lable: " + label + ", tag: " + tag + ", day: " + day);
}
//output: title: POTATO, lable: RANDOM, tag: FOOD, day: TODAY
If the string is dynamic then it can essentially contain basically anything and since there can possibly be no whitespace(s) in the string the only way to know what a specific word (substring) might be is to play the string against a 'word list'. You can quickly come to realize how pivotal even a single whitespace (or separator character) can be within a string. Using the String#substring() method is only good if you already know what all the words within the detail string happen to be.
The simple solution would be to set acceptable rules as to how a specific string should be received. After all, why would you want to accept a string that contains multiple words without a separator character of some type to begin with. If the string has whitespaces in it, to separate the words contained within that string, a mere:
String[] words = string.split("\\s+");
line of code would do the trick. Bottom line, get rid of that nonsense of accepting strings containing multiple words with no separation mechanism included, even if that separation mechanism is by making use of the underscore ( _ ) character (or some other character). Well...if you can.
I suppose sometimes we just can't modify how we're dealt things (something like taxes) and how we receive specific strings is simply out of our control. If this is the case then one way to deal with this dilemma is to work against an established Word-List. This word list can in in the size of a few words to hundreds of thousands of words. The situation you need to deal with will determine the word list size. If small enough the word list can be contained within a String Array or a collection like an ArrayList or List Interface. If really large however then the word list would most likely be contained within a Text file. The word list I most commonly use contains well over 370,000 individual words.
Here is an example of using a small Word-List contained within a List Interface:
String detail = "POTATORANDOMFOODTODAY";
List<String> wordList = Arrays.asList(new String[] {
"pumpkin", "carrot", "potato", "tomato", "lettus", "radish", "bean",
"pea", "food", "random", "today", "yesterday", "tomorrow",
});
// See if the detail string 'contains' any word-list words...
List<String> found = new ArrayList<>();
for (int i = 0; i < wordList.size(); i++) {
String word = wordList.get(i);
if (detail.toLowerCase().contains(word.toLowerCase())) {
found.add(word.toUpperCase());
}
}
/* Ensure the words within the list are in proper order.
That is, the same order as they are received within the
detail String. This is necessary since words from the
word-List can be found anywhere within the detail string. */
int startIndex = 0;
List<String> foundWords = new ArrayList<>();
String tmpStrg = "";
while (!tmpStrg.equals(detail)) {
for (int i = 0; i < found.size(); i++) {
String word = found.get(i);
if (detail.indexOf(word) == startIndex) {
foundWords.add(word);
startIndex = startIndex + word.length();
String procStrg = foundWords.toString().replace(", ", "");
tmpStrg = procStrg.substring(1, procStrg.length() - 1);
}
}
}
//Format and Display the required data
if (foundWords.isEmpty()) {
System.err.println("Couldn't find any required words!");
return; // or whatever...
}
String title = foundWords.get(0);
String label = foundWords.size() > 1 ? foundWords.get(1) : "N/A";
String[] tag = new String[1];
if (foundWords.size() > 2) {
tag = new String[foundWords.size()-2];
for (int i = 0; i < foundWords.size() - 2; i++) {
tag[i] = foundWords.get(i + 2);
}
}
else {
tag[0] = "N/A";
}
System.out.println("Title:\t" + title);
System.out.println("Label:\t" + label);
System.out.println("Tags:\t"
+ Arrays.toString(tag).substring(1, Arrays.toString(tag).length() - 1));
When the above code is run the console window would display:
Title: POTATO
Label: RANDOM
Tags: FOOD, TODAY
You can use the Stream API and use filter() method.
Then you use map() to apply your existing logic, that should do the trick.
Switch-cases could be an alternative but it adds more LoC but reduces the arrow code of all the nested ifs

return the first word in any string (Java)

I have to be able to input any two words as a string. Invoke a method that takes that string and returns the first word. Lastly display that word.
The method has to be a for loop method. I kind of know how to use substring, and I know how to return the first word by just using .substring(0,x) x being how long the first word is.
How can I make it so that no matter what phrase I use for the string, it will always return the first word? And please explain what you do, because this is my first year in a CS class. Thank you!
I have to be able to input any two words as a string
The zero, one, infinity design rule says there is no such thing as two. Lets design it to work with any number of words.
String words = "One two many lots"; // This will be our input
and then invoke and display the first word returned from the method,
So we need a method that takes a String and returns a String.
// Method that returns the first word
public static String firstWord(String input) {
return input.split(" ")[0]; // Create array of words and return the 0th word
}
static lets us call it from main without needing to create instances of anything. public lets us call it from another class if we want.
.split(" ") creates an array of Strings delimited at every space.
[0] indexes into that array and gives the first word since arrays in java are zero indexed (they start counting at 0).
and the method has to be a for loop method
Ah crap, then we have to do it the hard way.
// Method that returns the first word
public static String firstWord(String input) {
String result = ""; // Return empty string if no space found
for(int i = 0; i < input.length(); i++)
{
if(input.charAt(i) == ' ')
{
result = input.substring(0, i);
break; // because we're done
}
}
return result;
}
I kind of know how to use substring, and I know how to return the first word by just using .substring(0,x) x being how long the first word is.
There it is, using those methods you mentioned and the for loop. What more could you want?
But how can I make it so that no matter what phrase I use for the string, it will always return the first word?
Man you're picky :) OK fine:
// Method that returns the first word
public static String firstWord(String input) {
String result = input; // if no space found later, input is the first word
for(int i = 0; i < input.length(); i++)
{
if(input.charAt(i) == ' ')
{
result = input.substring(0, i);
break;
}
}
return result;
}
Put it all together it looks like this:
public class FirstWord {
public static void main(String[] args) throws Exception
{
String words = "One two many lots"; // This will be our input
System.out.println(firstWord(words));
}
// Method that returns the first word
public static String firstWord(String input) {
for(int i = 0; i < input.length(); i++)
{
if(input.charAt(i) == ' ')
{
return input.substring(0, i);
}
}
return input;
}
}
And it prints this:
One
Hey wait, you changed the firstWord method there.
Yeah I did. This style avoids the need for a result string. Multiple returns are frowned on by old programmers that never got used to garbage collected languages or using finally. They want one place to clean up their resources but this is java so we don't care. Which style you should use depends on your instructor.
And please explain what you do, because this is my first year in a CS class. Thank you!
What do I do? I post awesome! :)
Hope it helps.
String line = "Hello my name is...";
int spaceIndex = line.indexOf(" ");
String firstWord = line.subString(0, spaceIndex);
So, you can think of line as an array of chars. Therefore, line.indexOf(" ") gets the index of the space in the line variable. Then, the substring part uses that information to get all of the characters leading up to spaceIndex. So, if space index is 5, it will the substring method will return the indexes of 0,1,2,3,4. This is therefore going to return your first word.
The first word is probably the substring that comes before the first space. So write:
int x = input.indexOf(" ");
But what if there is no space? x will be equal to -1, so you'll need to adjust it to the very end of the input:
if (x==-1) { x = input.length(); }
Then use that in your substring method, just as you were planning. Now you just have to handle the case where input is the blank string "", since there is no first word in that case.
Since you did not specify the order and what you consider as a word, I'll assume that you want to check in given sentence, until the first space.
Simply do
int indexOfSpace = sentence.indexOf(" ");
firstWord = indexOfSpace == -1 ? sentence : sentence.substring(0, indexOfSpace);
Note that this will give an IndexOutOfBoundException if there is no space in the sentence.
An alternative would be
String sentences[] = sentence.split(" ");
String firstWord = sentence[0];
Of if you really need a loop,
String firstWord = sentence;
for(int i = 0; i < sentence.length(); i++)
{
if(sentence.charAt(i) == ' ')
{
sentence = firstWord.substring(0, i);
break;
}
}
You may get the position of the 'space' character in the input string using String.indexOf(String str) which returns the index of the first occurrence of the string in passed to the method.
E.g.:
int spaceIndex = input.indexOf(" ");
String firstWord = input.substring(0, spaceIndex);
Maybe this can help you figure out the solution to your problem. Most users on this site don't like doing homework for students, before you ask a question, make sure to go over your ISC book examples. They're really helpful.
String Str = new String("Welcome to Stackoverflow");
System.out.print("Return Value :" );
System.out.println(Str.substring(5) );
System.out.print("Return Value :" );
System.out.println(Str.substring(5, 10) );

Combine args into a sentence in Bukkit?

I am having trouble with something that seems so simple. How do i get a sentence from a command?
If a user entered : /command i want to get this with spaces minus the command and pressed enter, i would need to get this :
myString = "i want to get this with spaces minus the command";
How would i do this? A loop? And what would the the fastest, most efficient way to do this?
Thanks. This is what i have so far:
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (cmd.getName().equalsIgnoreCase("command"))
{
if(args.length > 0)
{
sender.sendMessage(ChatColor.RED + "/command <message>");
}
else
{
if (!(sender instanceof Player)) {
sender.sendMessage("This command can only be run by a player.");
}
else
{
Player player = (Player) sender;
// Check to make sure nothing is null or empty
if(args[0].equals(" ") || args[0].equals("") || args[0] == null)
{
// Do command !!
}
else
{
player.sendMessage(ChatColor.RED + "Please enter a <message>");
}
}
}
return true;
}
return false;
}
you could do this easily by using a for loop to get the all of the strings after the /command, which all are processed as arguments. Here's an example:
String myString = ""; //we're going to store the arguments here
for(int i = 0; i < args.length; i++){ //loop threw all the arguments
String arg = args[i] + " "; //get the argument, and add a space so that the words get spaced out
myString = myString + arg; //add the argument to myString
}
Now you have your string, and you could do anything with it, like send the message to the command sender:
sender.sendMessage(myString);
A short explanation of the code above is, first, we're looping threw all of the arguments (everything that comes after the /command, then, we're adding a space to the end of the argument, and last, we put the argument into the string, myString... Here's an example of implementation:
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if(cmd.getName().equalsIgnoreCase("command")){
String myString = "";
for(int i = 0; i < args.length(); i++){
String arg = args[i] + " ";
myString = myString + arg;
}
sender.sendMessage(myString); //send the message to the command sender.
}
}
you could also check if the command has arguments using:
if(args.length != 0){
An example when using a command is, let's say a player types /command bar foo. The player would then get sent the message bar foo.
Code:
String myString = "/command this is the text we want to grab right here";
myString = myString.subStr( myString.indexOf( ' ' ) + 1);
Explanation:
So if you have a String myString = "/command this is what we want", then you can seperate that first word by using .subStr(). subStr() has 2 versions, one with one parameter which is the starting point and gives you the string to the end, and another with two parameters which are the starting point and ending point and that gives you the string in between those locations.
Since we are getting the string from a certain position to the end, we are using the first method with one parameter. What will that parameter be? Well we know that the first character we want is right after the space after /command. So it is the location one after first space in the line. How do we get the location of the first space? Easy, String has a built in method indexOf() which can take in a String or a char and will return the location of the first occurrence of what we passed in.
We will pass in the char ' ' to indexOf(char c) since we want to find the location of the first space. Because once we know the location of the first space, we can go one after that and have the location of the start of what we need. Then we will pass that to subStr(int location) to get the string from that location to the end, and that is what we want.
So all of this sounds very complicated but the code is self explanatory:
String myString = "/command this is the text we want to grab right here";
myString = myString.subStr( myString.indexOf( ' ' ) + 1);
You could most easily do this with a String Builder.
public String getArgs(String[] args, int num){ //You can use a method if you want
StringBuilder sb = new StringBuilder(); //We make a String Builder
String prefix = ""; //We're going to store the space here
for(int i = num; i < args.length; i++) { //We get all the arguments with a for loop
sb.append(prefix); //We apply the space
prefix = " "; //We save the space in our prefix string
sb.append(args[i]); //We add the argument
}
return sb.toString(); //We return the message
}
or
public String getArgs(String[] args, int num){ //You can use a method if you want
StringBuilder sb = new StringBuilder(); //We make a String Builder
for(int i = num; i < args.length; i++) { //We get all the arguments with a for loop
sb.append(args[i]).append(" "); //We add the argument and the space
}
return sb.toString().trim(); //We return the message
}
I like this second method the most :3
The "int i = num" is the number of the argument we want to start to get them all, eg:
You have a command like this: /announce add message (message).
The message starts at args[2] so we'll do: getArgs(args, 2)
If you want to have one-word arguments before you have a multi-word argument you would want to loop through each argument starting at a certain one.
for(int i = 1; args.length > 1; i++){
String argsString = args[i] + " ";
}
To take all of the arguments given as one you just do this:
String argsString = args.toString();

Returning Words Within a String Array

I created a method to output a String. Using the split method and a for loop, I added each word in my sentence into a String array, replacxing the last two letters of each word with "ed". Now, my return statement should return each of the words. When I used System.out.print, it worked. When I use a return and call it in my main method, I get this output: "[Ljava.lang.String;#1b6235b"
The error seems so simple but I just don't know where I'm going worng. Any help would be appreciated.
Here is my method:
public String[] processInfo() {
String sentence = this.phrase;
String[] words = sentence.split(" ");
if (!this.phrase.equalsIgnoreCase("Fred")) {
for (int i = 0; i < words.length; i++) {
words[i] = words[i].substring(0, words[i].length() - 2).concat(
"ed ");
// System.out.print(words[i]);
}
}
return words;
}
You are printing arrays but arrays don't have a proper implementation of toString() method by default.
What you see is
"[Ljava.lang.String;#1b6235b"
This is [Ljava.lang.String; is the name for String[].class, the java.lang.Class representing the class of array of String followed by its hashCode.
In order to print the array you should use Arrays.toString(..)
System.out.println(Arrays.toString(myArray));
A good idea however, it returns my Strings in an Array format. My aim
is to return them back into sentence format. So for example, if my
input is, "Hey my name is Fred", it would output as, "Hed ed naed ed
Fred". Sorry, I forgot to add that it also seperates it with commas
when using Arrays.toString
Then you should modify your processInfo() returning a String or creating a new method that convert your String[] to a String.
Example :
//you use like this
String [] processInfoArray = processInfo();
System.out.println(myToString(processInfoArray));
// and in another part you code something like this
public static String myToString(String[] array){
if(array == null || array.length == 0)
return "";
StringBuilder sb = new StringBuilder();
for(int i=0;i<array.length-1;i++){
sb.append(array[i]).append(" ");
}
return sb.append(array[array.length -1]).toString();
}
As much as I can get from your question and comment is that your aim is to return them back into sentence format. So for example, if your input is, "Hey my name is Fred", it would output as, "Hed ed naed ed Fred".
In that case you should return a String, and not an array. I have modified your method a bit to do so. Let me know if you wanted something else.
public String processInfo() {
String sentence = this.phrase;
String[] words = sentence.split(" ");
if (!this.phrase.equalsIgnoreCase("Fred")) {
sentence = "";
for (int i = 0; i < words.length; i++) {
words[i] = words[i].substring(0, words[i].length() - 2).concat(
"ed ");
sentence += " " + words[i];
// System.out.print(words[i]);
}
}
return sentence.trim();
}
Your commented out call to System.out.print is printing each element of the array from inside the loop. Your method is returning a String[]. When you try to print an array, you will get the java representation of the array as you are seeing. You either need to change your method to build and return a string with all the array entries concatenated together, or your calling code needs to loop through the returned array and print each entry.

Why is the size of this vector 1?

When I use System.out.println to show the size of a vector after calling the following method then it shows 1 although it should show 2 because the String parameter is "7455573;photo41.png;photo42.png" .
private void getIdClientAndPhotonames(String csvClientPhotos)
{
Vector vListPhotosOfClient = new Vector();
String chainePhotos = "";
String photoName = "";
String photoDirectory = new String(csvClientPhotos.substring(0, csvClientPhotos.indexOf(';')));
chainePhotos = csvClientPhotos.substring(csvClientPhotos.indexOf(';')+1);
chainePhotos = chainePhotos.substring(0, chainePhotos.lastIndexOf(';'));
if (chainePhotos.indexOf(';') == -1)
{
vListPhotosOfClient.addElement(new String(chainePhotos));
}
else // aaa;bbb;...
{
for (int i = 0 ; i < chainePhotos.length() ; i++)
{
if (chainePhotos.charAt(i) == ';')
{
vListPhotosOfClient.addElement(new String(photoName));
photoName = "";
continue;
}
photoName = photoName.concat(String.valueOf(chainePhotos.charAt(i)));
}
}
}
So the vector should contain the two String photo41.png and photo42.png , but when I print the vector content I get only photo41.png.
So what is wrong in my code ?
The answer is not valid for this question anymore, because it has been retagged to java-me. Still true if it was Java (like in the beginning): use String#split if you need to handle csv files.
It's be far easier to split the string:
String[] parts = csvClientPhotos.split(";");
This will give a string array:
{"7455573","photo41.png","photo42.png"}
Then you'd simply copy parts[1] and parts[2] to your vector.
You have two immediate problems.
The first is with your initial manipulation of the string. The two lines:
chainePhotos = csvClientPhotos.substring(csvClientPhotos.indexOf(';')+1);
chainePhotos = chainePhotos.substring(0, chainePhotos.lastIndexOf(';'));
when applied to 7455573;photo41.png;photo42.png will end up giving you photo41.png.
That's because the first line removes everything up to the first ; (7455573;) and the second strips off everything from the final ; onwards (;photo42.png). If your intent is to just get rid of the 7455573; bit, you don't need the second line.
Note that fixing this issue alone will not solve all your ills, you still need one more change.
Even though your input string (to the loop) is the correct photo41.png;photo42.png, you still only add an item to the vector each time you encounter a delimiting ;. There is no such delimiter at the end of that string, meaning that the final item won't be added.
You can fix this by putting the following immediately after the for loop:
if (! photoName.equals(""))
vListPhotosOfClient.addElement(new String(photoName));
which will catch the case of the final name not being terminated with the ;.
These two lines are the problem:
chainePhotos = csvClientPhotos.substring(csvClientPhotos.indexOf(';') + 1);
chainePhotos = chainePhotos.substring(0, chainePhotos.lastIndexOf(';'));
After the first one the chainePhotos contains "photo41.png;photo42.png", but the second one makes it photo41.png - which trigers the if an ends the method with only one element in the vector.
EDITED: what a mess.
I ran it with correct input (as provided by the OP) and made a comment above.
I then fixed it as suggested above, while accidently changing the input to 7455573;photo41.png;photo42.png; which worked, but is probably incorrect and doesn't match the explanation above input-wise.
I wish someone would un-answer this.
You can split the string manually. If the string having the ; symbol means why you can do like this? just do like this,
private void getIdClientAndPhotonames(String csvClientPhotos)
{
Vector vListPhotosOfClient = split(csvClientPhotos);
}
private vector split(String original) {
Vector nodes = new Vector();
String separator = ";";
// Parse nodes into vector
int index = original.indexOf(separator);
while(index>=0) {
nodes.addElement( original.substring(0, index) );
original = original.substring(index+separator.length());
index = original.indexOf(separator);
}
// Get the last node
nodes.addElement( original );
return nodes;
}

Categories

Resources