Replacing symbol with a number - java

I want to read a file and detect if the character after the symbol is a number or a word. If it is a number, I want to delete the symbol in front of it, translate the number into binary and replace it in the file. If it is a word, I want to set the characters to number 16 at first, but then, if another word is used, I want to add the 1 to the original number. Here's what I want:
If the file name reads (... represents a string that does not need to be translated):
%10
...
%firststring
...
%secondstring
...
%firststring
...
%11
...
and so on...
I want it to look like this:
0000000000001010 (10 in binary)
...
0000000000010000 (16 in binary)
...
0000000000010001 (another word was used, so 16+1 = 17 in binary)
...
0000000000010000 (16 in binary)
...
0000000000001011 (11 in binary)
And here's what I tried:
anyLines is just a string array which has the contents of the file (if I were to say System.out.println(anyLines[i]), I would the file's contents printed out).
UPDATED!
try {
ReadFile files = new ReadFile(file.getPath());
String[] anyLines = files.OpenFile();
int i;
int wordValue = 16;
// to keep track words that are already used
Map<String, Integer> wordValueMap = new HashMap<String, Integer>();
for (String line : anyLines) {
// if line doesn't begin with &, then ignore it
if (!line.startsWith("#")) {
continue;
}
// remove
line = line.substring(1);
Integer binaryValue = null;
if (line.matches("\\d+")) {
binaryValue = Integer.parseInt(line);
}
else if (line.matches("\\w+")) {
binaryValue = wordValueMap.get(line);
// if the map doesn't contain the word value, then assign and store it
if (binaryValue == null) {
binaryValue = wordValue;
wordValueMap.put(line, binaryValue);
++wordValue;
}
}
// I'm using Commons Lang's StringUtils.leftPad(..) to create the zero padded string
System.out.println(Integer.toBinaryString(binaryValue));
}
Now, I only have to replace the symbols (%10, %firststring, etc) with the binary value.
After executing this code, what I get as the output is:
1010
10000
10001
10000
1011
%10
...
%firststring
...
%secondstring
...
%firststring
...
%11
...
Now I just need to replace the %10 with 1010, the %firststring with 10000 and so on, so that the file would read like this:
0000000000001010 (10 in binary)
...
0000000000010000 (16 in binary)
...
0000000000010001 (another word was used, so 16+1 = 17 in binary)
...
0000000000010000 (16 in binary)
...
0000000000001011 (11 in binary)
Do you have any suggestions on how to make this work?

This may not be doing what you think it's doing:
int binaryValue = wordValue++;
Because you are using the post-increment operator, binary value is being assigned the old worldValue value, and then worldValue is incremented. I'd do this on two separate lines with the increment being done first:
wordValue++;
int binaryValue = wordValue; // binaryValue now gets the new value for wordValue
EDIT 1
OK, if you still need our help, I suggest you do the following:
Show us a sample of the data file so we can see what it actually looks like.
Explain the difference between the anyLines array and the lines array and how they relate to the data file. They both have Strings, and lines is obviously the result of splitting anyLines with "\n" but what again is anyLines. You state that the file is a text file, but how do you get the initial array of Strings from this text file? Is there another delimiter that you use to get this array? Have you tried to debug the code by printing out the contents of anyLines and lines?
If you need wordValue to persist with each iteration of a loop through anyLines (again, knowing what this is would help), you will need to declare and initialize it before the loop.
If you can't create and post an SSCCE, at least make your code formatting consistent and readable, something like the code below.
Have a look at the link on how to ask smart questions for more tips on information that you could give us that would help us to help you.
Sample code formatting:
try {
ReadFile files = new ReadFile(file.getPath());
String[] anyLines = files.OpenFile();
String[] anyLines = {};
int i;
// test if the program actually read the file
for (i = 0; i < anyLines.length; i++) {
String[] lines = anyLines[i].split("\n");
int wordValue = 76;
Map<String, Integer> wordValueMap = new HashMap<String, Integer>();
for (String currentLine : lines) {
if (!currentLine.startsWith("%")) {
continue;
}
currentLine = currentLine.substring(1);
Integer value;
if (currentLine.matches("\\d+")) {
value = Integer.parseInt(currentLine);
} else if (currentLine.matches("\\w+")) {
value = wordValueMap.get(currentLine);
if (value == null) {
int binaryValue = wordValue++;
wordValueMap.put(currentLine, binaryValue);
// TODO: fix below
// !! currentLine.replace(currentLine, binaryValue);
value = binaryValue;
}
} else {
System.out.println("Invalid input");
break;
}
System.out.println(Integer.toBinaryString(value));
}
}
} finally {
// Do we need a catch block? If so, catch what?
// What's supposed to go in here?
}
Luck!

Related

Count occurrences in 2D Array

I'm trying to count the occurrences per line from a text file containing a large amount of codes (numbers).
Example of text file content:
9045,9107,2376,9017
2387,4405,4499,7120
9107,2376,3559,3488
9045,4405,3559,4499
I want to compare a similar set of numbers that I get from a text field, for example:
9107,4405,2387,4499
The only result I'm looking for, is if it contains more than 2 numbers (per line) from the text file. So in this case it will be true, because:
9045,9107,2376,9017 - false (1)
2387,4405,4499,7120 - true (3)
9107,2387,3559,3488 - false (2)
9045,4425,3559,4490 - false (0)
From what I understand, the best way to do this, is by using a 2d-array, and I've managed to get the file imported successfully:
Scanner in = null;
try {
in = new Scanner(new File("areas.txt"));
} catch (FileNotFoundException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
List < String[] > lines = new ArrayList < > ();
while ( in .hasNextLine()) {
String line = in .nextLine().trim();
String[] splitted = line.split(", ");
lines.add(splitted);
}
String[][] result = new String[lines.size()][];
for (int i = 0; i < result.length; i++) {
result[i] = lines.get(i);
}
System.out.println(Arrays.deepToString(result));
The result I get:
[[9045,9107,2376,9017], [2387,4405,4499,7120], [9107,2376,3559,3488], [9045,4405,3559,4499], [], []]
From here I'm a bit stuck on checking the codes individually per line. Any suggestions or advice? Is the 2d-array the best way of doing this, or is there maybe an easier or better way of doing it?
The expected number of inputs defines the type of searching algorithm you should use.
If you aren't searching through thousands of lines then a simple algorithm will do just fine. When in doubt favour simplicity over complex and hard to understand algorithms.
While it is not an efficient algorithm, in most cases a simple nested for-loop will do the trick.
A simple implementation would look like this:
final int FOUND_THRESHOLD = 2;
String[] comparedCodes = {"9107", "4405", "2387", "4499"};
String[][] allInputs = {
{"9045", "9107", "2376", "9017"}, // This should not match
{"2387", "4405", "4499", "7120"}, // This should match
{"9107", "2376", "3559", "3488"}, // This should not match
{"9045", "4405", "3559", "4499"}, // This should match
};
List<String[] > results = new ArrayList<>();
for (String[] input: allInputs) {
int numFound = 0;
// Compare the codes
for (String code: input) {
for (String c: comparedCodes) {
if (code.equals(c)) {
numFound++;
break; // Breaking out here prevents unnecessary work
}
}
if (numFound >= FOUND_THRESHOLD) {
results.add(input);
break; // Breaking out here prevents unnecessary work
}
}
}
for (String[] result: results) {
System.out.println(Arrays.toString(result));
}
which provides us with the output:
[2387, 4405, 4499, 7120]
[9045, 4405, 3559, 4499]
To expand on my comment, here's a rough outline of what you could do:
String textFieldContents = ... //get it
//build a set of the user input by splitting at commas
//a stream is used to be able to trim the elements before collecting them into a set
Set<String> userInput = Arrays.stream(textFieldContents .split(","))
.map(String::trim).collect(Collectors.toSet());
//stream the lines in the file
List<Boolean> matchResults = Files.lines(Path.of("areas.txt"))
//map each line to true/false
.map(line -> {
//split the line and stream the parts
return Arrays.stream(line.split(","))
//trim each part
.map(String::trim)
//select only those contained in the user input set
.filter(part -> userInput.contains(part))
//count matching elements and return whether there are more than 2 or not
.count() > 2l;
})
//collect the results into a list, each element position should correspond to the zero-based line number
.collect(Collectors.toList());
If you need to collect the matching lines instead of a flag per line you could replace map() with filter() (same content) and change the result type to List<String>.

Reading in stops after handling exception inside loop

I'd have a pretty strange question here. After throwing and handling my ReaderException exception my read-in still stops at the first occurence of the exception. Can somebody please explain why is this happening?
Input:
Hotel Paradis;Strada Ciocarliei, Cluj-Napoca 400124;46.779862;23.611739;7;200;8;250;1;400
Hotel Sunny Hill;Strada Fagetului 31A, Cluj-Napoca 400497;46.716030;23.573740;4;150;6;190
Golden Tulip Ana Dome;Strada Observatorului 129, Cluj-Napoca 400352;46.751989;23.576580;0;330;0;350;0;600
Code:
public HotelDescriptor readLine(final String line) throws ReaderException {
System.out.println(line);
String info[] = line.split(";");
for (String i:info)
System.out.println(i);
String tempname = info[0];
String tempaddress = info[1];
float templatitudeh = Float.parseFloat(info[2]);
float templongitudeh = Float.parseFloat(info[3]);
int singleroom = Integer.parseInt(info[4]);
int singleprice = Integer.parseInt(info[5]);
int doubleroom = Integer.parseInt(info[6]);
int doubleprice = Integer.parseInt(info[7]);
int suiteroom = Integer.parseInt(info[8]);
int suiteprice = Integer.parseInt(info[9]);
Hotel tempHotel = new Hotel(tempname, tempaddress, templatitudeh, templongitudeh, singleroom, singleprice, doubleroom, doubleprice, suiteroom, suiteprice);
System.out.println(tempHotel.getName());
return tempHotel;
}
public List<HotelDescriptor> readFile(final String hotels) {
try (BufferedReader buff = new BufferedReader(new FileReader(hotels))) {
String line = "";
while ((line = buff.readLine() )!= null) {try {
hotelData.add(readLine(line));
} catch (ReaderException e){
e.printStackTrace();
} catch (ArrayIndexOutOfBoundsException ex){
ex.printStackTrace();
}
//line = buff.readLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return hotelData;
}
I take it that hotelData is declared as a Class field (class global).
When reading in a text file you should take into consideration some anomalies that can happen (or not). Simple steps can be taken to ensure that reading of that text file will be relatively successful. If your application is creating the text file then your success rate raises considerably since you can control how it is written but, if your application is not creating the text file or the text file is compiled from remote sources then the success rate can be reduced unless steps are taken to ensure expected results.
In my opinion:
A text file should be identifiable so as to ensure that the proper
text file is actually being read to process. If the text data is from
a CSV file then a CSV Header line should be the very first line
within the file and a read of this line should be done and compared
to so as to verify that the correct file is being accessed. This is
especially true if the file is to be selectable by any number of
Users (perhaps by way of a file chooser). If a File Identifier
(or Descriptor) line does not exist within your text file as the first line of
the file then perhaps you should consider using one even if it is
considered a Comment Line where the line might start with perhaps
a semi-colon (;) as the first character of the line. Anything
that can identify the file as being the correct file to process.
Blank lines and any lines deemed to be Comment Lines should be
ignored. This includes any file lines known not to be actual Data
Lines whatever they may be. In general, a couple lines of code
consisting of an if statement along with a few conditions can
take care of this situation.
Never count on actual Data Lines (the lines of data you will be
processing) to be holding all the required data expected. This is
especially true when manipulating split delimited data with
methods such as Integer.parseInt() or Float.parseFloat() as a
mere examples. This is actually the biggest problem in your particular
situation. Take note of the example data lines you have provided
within your post. The first line consists of 10 delimited pieces of
data, the second data line consists of 8 delimited pieces of
data, and the third line consists of again, 10 pieces of delimited
data. It is the second data line that is the issue here. When
this line is split the result will be an Array (info[]) which
will hold 8 elements (index 0 to 7) yet the readLine() method is
expecting to always deal with an array consisting of 10 elements
(index 0 to 9). While processing the second data line, guess what
happens when the code line int suiteroom = Integer.parseInt(info[8]); is hit. That's right, you get a
ArrayIndexOutOfBoundsException because there simply is no index 8 within the info[] array. You need to handle situations like this in your code and prepare to deal with them. Don't rely on
exception handling to take care of business for you. The whole idea
is to avoid exceptions if at all possible mind you there are times when it is necessary. I don't believe this is one of them.
Without access to your code classes I'm just going to naturally assume that your method returns are valid and functioning as planned. With this in mind, here is how I would format the Hotels text file:
My App Name - Hotels Data File
;Hotel Name; Hotel Address; Latitude; Longtitude; Single Room; Single Price; Double Room; Double Price; Suite Room; Suite Price
Hotel Paradis;Strada Ciocarliei, Cluj-Napoca 400124;46.779862;23.611739;7;200;8;250;1;400
Hotel Sunny Hill;Strada Fagetului 31A, Cluj-Napoca 400497;46.716030;23.573740;4;150;6;190
Golden Tulip Ana Dome;Strada Observatorului 129, Cluj-Napoca 400352;46.751989;23.576580;0;330;0;350;0;600
The first line of the file is the File Descriptor line. The second line is a Blank Line simply for easier viewing of the file. The third line is considered a Comment Line because in this case it starts with a semi-colon (;). It's actually up to you to decide what is to be in place to make a file line considered as a Comment line. This line simply acts as a Header Line and describes what each delimited piece of data on any Data Line means. The fourth line is of course yet another blank line and again, for easier viewing of the file. The remaining file lines are all Data Lines and these are the file lines you want to process.
To read the file your methods might look like this:
public HotelDescriptor readLine(final String line) {
// Split on various possible combinations of how the
// delimiter might be formated within a file line.
String info[] = line.split(" ; |; |;");
// Variables declaration and default initialization values
String tempname = "";
String tempaddress = "";
float templatitudeh = 0.0f;
float templongitudeh = 0.0f;
int singleroom = 0;
int singleprice = 0;
int doubleroom = 0;
int doubleprice = 0;
int suiteroom = 0;
int suiteprice = 0;
String strg; // Used to hold the current Array Element in the for/loop
String regExF = "-?\\d+(\\.\\d+)?"; // RegEx to validate a string float or double value.
String regExI = "\\d+"; // RegEx to validate a string Integer value.
for (int i = 0; i < info.length; i++) {
strg = info[i].trim(); // remove leading/trailing spaces if any
switch (i) {
case 0:
tempname = info[i];
break;
case 1:
tempaddress = info[i];
break;
case 2:
// Is it a float or double numerical value
if (strg.matches(regExF)) {
templatitudeh = Float.parseFloat(info[i]);
}
break;
case 3:
// Is it a float or double numerical value
if (strg.matches(regExF)) {
templongitudeh = Float.parseFloat(info[i]);
}
break;
case 4:
// Is it a Integer numerical value
if (strg.matches(regExI)) {
singleroom = Integer.parseInt(info[i]);
}
break;
case 5:
// Is it a Integer numerical value
if (strg.matches(regExI)) {
singleprice = Integer.parseInt(info[i]);
}
break;
case 6:
// Is it a Integer numerical value
if (strg.matches(regExI)) {
doubleroom = Integer.parseInt(info[i]);
}
break;
case 7:
// Is it a Integer numerical value
if (strg.matches(regExI)) {
doubleprice = Integer.parseInt(info[i]);
}
break;
case 8:
// Is it a Integer numerical value
if (strg.matches(regExI)) {
suiteroom = Integer.parseInt(info[i]);
}
break;
case 9:
// Is it a Integer numerical value
if (strg.matches(regExI)) {
suiteprice = Integer.parseInt(info[i]);
}
break;
}
}
Hotel tempHotel = new Hotel(tempname, tempaddress, templatitudeh, templongitudeh,
singleroom, singleprice, doubleroom, doubleprice, suiteroom, suiteprice);
System.out.println(tempHotel.getName());
return tempHotel;
}
public List<HotelDescriptor> readFile(final String hotels) {
try (BufferedReader buff = new BufferedReader(new FileReader(hotels))) {
String line;
int lineCounter = 0;
while ((line = buff.readLine()) != null) {
// Trim any leading or trailing spaces (spaces, tabs, etc)
line = line.trim();
lineCounter++;
// Is this the right file to read?
if (lineCounter == 1) {
if (!line.equalsIgnoreCase("My App Name - Hotels Data File")) {
//No it isn't...
JOptionPane.showMessageDialog(this, "Invalid Hotels Data File!",
"Invalid Data File", JOptionPane.WARNING_MESSAGE);
break; // Get out of while loop
}
// Otherwise skip the File Descriptor line.
else { continue; }
}
// Is this a blank or Comment line...
// Lines that start with ; are comment lines
if (line.equals("") || line.startsWith(";")) {
// Yes it is...skip this line.
continue;
}
// Process the data line...
hotelData.add(readLine(line));
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return hotelData;
}
In the readLine() method variables are initialized to hold default values should not all values be present on any given file Data Line. The switch block ensures that only supplied data line values are processed regardless of how data is provided, defaults fill in the rest. This eliminates the possibility of an ArrayIndexOutOfBoundsException from happening when working with the info[] Array.
Where parseFloat() and parseInt() are used the string to be converted into its respective data type is first checked to ensure that it is a valid numerical representation of the data type we are converting to. The String.matches() method is used for this in conjunction with a regular expression.
The code above can of course be optimized much further but I feel it provides a good description of what can be done to to increase the success of reading and processing the file(s).
As a side note, it is also understandably confusing to call one of your own methods (readLine()) by the same name as a method used by BufferedReader. Up to you but perhaps this would be better named as processReadLine()
Prices should be at least in either float or double data type

Java Concordance Exercise

So I have a programming exercise that involves concordance. I am attempting to take a .txt file, use regex to parse it into strings containing all words, then create a Hashtable that has the key (the word) and the value (the number of times the word appears in the document). We are supposed to be able to account for both case sensitive and non-case sensitive scenarios by passing in a boolean.
Here is what I have:
public Concordance( String pathName, boolean is_case_sensitive ) {
Scanner file = new Scanner(pathName);
try {
file = new Scanner(new File(pathName));
} catch (FileNotFoundException e) {
System.out.println("No File Found");
}
String[] words;
Pattern pattern = Pattern.compile("\\W+");
words = pattern.split(file.nextLine());
String[] wordsCopy = new String[words.length];
for (int i = 0; i < words.length; i++){
wordsCopy[i] = new String(words[i]);
}
int counter = 0;
while (file.hasNext()){
for (String w : words){
counter = 0;
for (String w2 : wordsCopy){
if (is_case_sensitive == false){
if (w.equalsIgnoreCase(w2)){
counter++;
//w2 = null;
tableOfWords.put(w, counter);
file.next();
}
}
if (is_case_sensitive == true){
if (w.equals(w2)){
counter++;
//w2 = null;
tableOfWords.put(w, counter);
file.next();
}
}
}
}
}
}
To walk you through where I am and where my error I believe is....
I use the scanner to "take in" the file the use the regex \W+ to get all of words. I create a String array, I split the Pattern pattern into the String array. Then I create a deep copy of the array to use during comparison. (So I now have two String arrays - words and wordsCopy). I use an int counter variable to keep track of how many times it appears and address case sensitivity by using an if statement and the equals/equalsIgnoreCase methods. I have been going back and forth between assigning w2 to null (its currently commented out) as I intuitively feel like if it is not set to null, it will be counted twice, but I can't seem to think through it appropriately. I think I am counting items in duplicate, but can't seem to figure out a solution. Any insight? Thanks!
You dont need any extra String[] to check case sensitive
Pattern pattern = Pattern.compile("\\W+");
HashMap<String, AtomicInteger> tableOfWords = new HashMap<String, AtomicInteger>();
while (file.hasNextLine()){
words = pattern.split(file.nextLine());
for (String w : words){
String tmp = w;
if (!is_case_sensitive){
tmp = String.valueOf(w.toLowerCase());
}
AtomicInteger count = tableOfWords.get(tmp);
if (count == null){
count = new AtomicInteger(0);
}
count.incrementAndGet();
tableOfWords.put(tmp,count);
}
}
Convert the actual word into low / high case if case sensitive is not required. then everything work perfectly.
As far as I can see you are actually counting words multiple times (more than twice aswell)
I'll give you a simple foreach loop to explain what you're doing,
some of the syntax might be wrong as i'm not using an ide to write this code
int[5] ints = {1,2,3,4,5};
int[5] intcopy = ints;
for(int i:ints){
for(int j: intcopy){
system.out.println(j);
}
}
What you will end out printing is
1
2
3
4
5
1
2
3
4
5
1
2
3
4
5
1
2
3
4
5
1
2
3
4
5
1
2
3
4
5
So instead of counting 5 things you are counting 25 things, hope this helps

Storing input from text file

My question is quite simple, I want to read in a text file and store the first line from the file into an integer, and every other line of the file into a multi-dimensional array. The way of which I was thinking of doing this would be of creating an if-statement and another integer and when that integer is at 0 store the line into the integer variable. Although this seems stupid and there must be a more simple way.
For example, if the contents of the text file were:
4
1 2 3 4
4 3 2 1
2 4 1 3
3 1 4 2
The first line "4", would be stored in an integer, and every other line would go into the multi-dimensional array.
public void processFile(String fileName){
int temp = 0;
int firstLine;
int[][] array;
try{
BufferedReader input = new BufferedReader(new FileReader(fileName));
String inputLine = null;
while((inputLine = input.readLine()) != null){
if(temp == 0){
firstLine = Integer.parseInt(inputLine);
}else{
// Rest goes into array;
}
temp++;
}
}catch (IOException e){
System.out.print("Error: " + e);
}
}
I'm intentionally not answering this to do it for you. Try something with:
String.split
A line that says something like array[temp-1] = new int[firstLine];
An inner for loop with another Integer.parseInt line
That should be enough to get you the rest of the way
Instead, you could store the first line of the file as an integer, and then enter a for loop where you loop over the rest of the lines of the file, storing them in arrays. This doesn't require an if, because you know that the first case happens first, and the other cases (array) happen after.
I'm going to assume that you know how to use file IO.
I'm not extremely experienced, but this is how I would think about it:
while (inputFile.hasNext())
{
//Read the number
String number = inputFile.nextLine();
if(!number.equals(" ")){
//Do what you need to do with the character here (Ex: Store into an array)
}else{
//Continue on reading the document
}
}
Good Luck.

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