Loop not iterating full length - java

I'm passing a String to a method that has commas in as delimiters.
"TMJ,Emma,Sarah"
I tokenize this String using ',' as the regular expression to split.
I then iterate the length of the tokenized array comparing each element against a HashMap of all possible values. If the value being tested is a key in the HashMap then i get the key's value and store that in another String.
I want to append each value of the key to the String that holds the values.
It seems to iterate only once, then jumps out of the loop and returns only the first thing it finds in the hashmap.
Could anyone explain why? Thanks in advance Matt.
public static String getrecipientIntergerValues(String recipient) {
Log.e(TAG, "recipient string list passed in to app obj = " + recipient);
String[] tokenizedRecipient = recipient.split(",");
String recipientAsInteger = "";
for(int i = 0; i < tokenizedRecipient.length; i++){
Log.e(TAG, "tokenizedRecipient = " + tokenizedRecipient[i].toString());
}
Log.e(TAG, "tokenizedRecipient length = " + tokenizedRecipient.length);
for(int i = 0; i < tokenizedRecipient.length; i++){
if(recipients.containsKey(tokenizedRecipient[i].toString())){
Log.e(TAG, "hashmap contains key " + tokenizedRecipient[i].toString() + "with value " + recipients.get(tokenizedRecipient[i].toString()));
String integerValueOfName = recipients.get(tokenizedRecipient[i].toString());
recipientAsInteger = recipientAsInteger + integerValueOfName + ",";
}
}
Log.e(TAG, "recipient list as integers = " + recipientAsInteger);
return recipientAsInteger;
}
.
09-20 16:33:51.039: E/NfcScannerApplication(25835): recipient string list passed in to app obj = Emma, TMJ,
09-20 16:33:51.039: E/NfcScannerApplication(25835): tokenizedRecipient = Emma
09-20 16:33:51.064: E/NfcScannerApplication(25835): tokenizedRecipient = TMJ
09-20 16:33:51.064: E/NfcScannerApplication(25835): tokenizedRecipient =
09-20 16:33:51.079: E/NfcScannerApplication(25835): tokenizedRecipient length = 3
09-20 16:33:51.079: E/NfcScannerApplication(25835): hashmap contains key Emmawith value 3
09-20 16:33:51.089: E/NfcScannerApplication(25835): recipient list as integers = 3,

Your logging suggests that the string you are passing is "Emma, TMJ, " which is not what you suggest.
09-20 16:33:51.039: ... recipient string list passed in to app obj = Emma, TMJ,
I believe the solution to your problem would be to use String.split(",",0) as this will remove empty strings at the end. You may also wish to use String.trim() before looking up the string in your map.

Without seeing what recipients contains, you can safely assume that
if(recipients.containsKey(tokenizedRecipient[i].toString())){
Log.e(TAG, "hashmap contains key " + tokenizedRecipient[i].toString() + "with value " + recipients.get(tokenizedRecipient[i].toString()));
String integerValueOfName = recipients.get(tokenizedRecipient[i].toString());
recipientAsInteger = recipientAsInteger + integerValueOfName + ",";
}
only executes once because recipients only contains a key for Emma. The for loop loops 3 times, but only matches the if once.
If your recipients map contains keys for Emma and TMJ then you're problem is your split() method, take a look at the other answers.

If the input string is "Emma, TMJ," then the split will return an array containing these two strings:
"Emma"
" TMJ"
The last one will not match "TMJ". Try using ", *" (or, better, "\\s*,\\s*") as the regex to use for split (this will treat extra spaces as part of the delimiter and not include them in the resulting strings); or use the .trim() method on the resulting strings (which removes leading and trailing whitespace).

Related

Two strings appear to be equal, but they are not

I want to open a file using the argument I get via a socket. When I extract the filename using split(), the file does not open. But when I hardcode the value, it does open.
What am I missing here? I would expect the strings to be equal.
String name = str.split(";")[2];
System.out.println("Filename: " + name);
String path1 = new String("Input_Blatt3/Sample.txt");
String path2 = new String("Input_Blatt3/" + name);
System.out.println("Path1: " + path1);
System.out.println("Path2: " + path2);
System.out.println("path1.equals(path2) = " + path1.equals(path2));
Output:
Path1: Input_Blatt3/Sample.txt
Path2: Input_Blatt3/Sample.txt
path1.equals(path2) = false
There could be unprintable characters hidden in the String.
Use getBytes to get all the characters of a String and print those. You'll probably find something you didn't expect.
You need to iterate over the byte array to print each byte individually, as in the following method:
private static void printBytes(String string) {
System.out.println("printing " + string);
for (byte aByte : string.getBytes()) {
System.out.println( aByte );
}
}
Alternatively you could also replace everything that isn't a printable character with nothing.
There could be some trailing white spaces, which you would not see at the console output.
You can try name.strip() (or trim() if your JDK version is lower 11) to ensure that there's nothing but the file name in the string.
Also, you can find the index of the first mismatching character of these two strings using Arrays.mismatch():
int indexOfMismatch = Arrays.mismatch(str1.toCharArray(), str2.toCharArray());
In case if the strings are equal, indexOfMismatch would be -1.

Get a specific data values from a string in Java (String without comma)

I want to get the value from a string.
I have a string value like this:
String myData= "Number: 34678 Type: Internal Qty: 34";
How can I get the Number, Type, Qty values separately?
Give me any suggestion on this.
Input:
String myData= "Number: 34678 Type: Internal Qty: 34";
Output:
Number value is 34678
Type values is Internal
Qty value is 34
Here is one way to do it. It looks for a word following by a colon followed by zero or more spaces followed by another word. This works regardless of the order or names of the fields.
String myData = "Number: 34678 Type: Internal Qty: 34";
Matcher m = Pattern.compile("(\\S+):\\s*(\\S+)").matcher(myData);
while (m.find()) {
System.out.println(m.group(1) + " value is " + m.group(2));
}
You can use regex to do this cleanly:
Pattern p = Pattern.compile("Number: (\\d*) Type: (.*) Qty: (\\d*)");
Matcher m = p.matcher(myData);
m.find()
So you'll get the number with m.group(1), the Type m.group(2) and the Qty m.group(3).
I assume you accept a limited number of types. So you can change the regex to match only if the type is correct, for eg. either Internal or External: "Number: (\\d*) Type: (Internal|External) Qty: (\\d*)"
Here's a nice explanation of how this works
If you just want to print them with fixed pattern of input data, a simplest way is shown as follows: (Just for fun!)
System.out.print(myData.replace(" Type", "\nType")
.replace(" Qty", "\nQty")
.replace(":", " value is"));
I suppose the string is always formatted like that. I.e., n attribute names each followed by a value that does not contain spaces. In other words, the 2n entities are separated from each other by 1 or more spaces.
If so, try this:
String[] parts;
int limit;
int counter;
String name;
String value;
parts = myData.split("[ ]+");
limit = (parts.length / 2) * 2; // Make sure an even number of elements is considered
for (counter = 0; counter < limit; counter += 2)
{
name = parts[counter].replace(":", "");
value = parts[counter + 1];
System.out.println(name + " value is " + value);
}
This Should work
String replace = val.replace(": ", "|");
StringBuilder number = new StringBuilder();
StringBuilder type = new StringBuilder();
StringBuilder qty = new StringBuilder();
String[] getValues = replace.split(" ");
int i=0;
while(i<getValues.length-1){
String[] splitNumebr = getValues[i].split("\\|");
number.append(splitNumebr[1]);
String[] splitType = getValues[i+=1].split("\\|");
type.append(splitType[1]);
String[] splitQty = getValues[i+=1].split("\\|");
qty.append(splitQty[1]);
}
System.out.println(String.format("Number value is %s",number.toString()));
System.out.println(String.format("Type value is %s",type.toString()));
System.out.println(String.format("Qty value is %s",qty.toString()));
}
Output
Number value is 34678
Type value is Internal
Qty value is 34

How to remove blank lines in middle of a string Android

String Address[] = mSelectedaddress.split("\\|");
address.setText(
Address[1] + "\n"
+ Address[2] + "\n"
+ Address[3] + "\n"
+ Address[4]);
Actual Output:
Address 1
Address 2
=> Blank line
City
Wanted Output:
Address 1
Address 2
City
If u can see my above code there are some scenario where Address[positon] may return blank text that time how can i remove that line if it is blank.
String adjusted = adress.replaceAll("(?m)^[ \t]*\r?\n", "");
When you build your string, check to see if the string is empty before you add it.
StringBuilder builder = new StringBuilder();
for(int it = 0; i < Address.length; i++) {
if(Address[i] != "")
builder.append(Address[i]);
}
address.setText(builder.toString());
}
The simplest thing I can think of that should do the trick most of the time:
mSelectedaddress.replaceAll("[\\|\\s]+", "|").split("\\|");
This will remove multiple |'s (with or without spaces) in a row. Those are the cause of your empty lines.
Example:
"a|b|c|d|e||g" -> works
"a|b|c|d|e| |g" -> works
"a|b|c|d|e|||g" -> works

how to generate string with varying number of spaces OR how to add no of spaces after a string

I need help to generate empty string with particular no of spaces.
I tried this,
String opCode= " ";
for(int l=0;l<opCodelen;l++)
{
opCode+= " " ;
}
//opCodelen will get change every time
This worked but I want better solution.becoz using this I will have to use multiple loops for multiple columns.Is there any other way to do this?
Try String.format()
int opCodelen = 5;
String opCode = String.format("%" + opCodelen + "s", "");
System.out.println("[" + opCode + "]");
output
[ ]
Another way (uglier but for many probably simpler) to solve it could be
creating array of characters with same length as number of spaces you want to end up with,
filling it with spaces
and passing it as argument in String constructor.
Something like
char[] arr = new char[10]; // lets say length of string should be 10
Arrays.fill(arr, ' '); // fill array with spaces
String mySpaceString = new String(arr);
System.out.println(">" + mySpaceString + "<");
output:
> <

Java add chars to a string

I have two strings in a java program, which I want to mix in a certain way to form two new strings. To do this I have to pick up some constituent chars from each string and add them to form the new strings. I have a code like this(this.eka and this.toka are the original strings):
String muutettu1 = new String();
String muutettu2 = new String();
muutettu1 += this.toka.charAt(0) + this.toka.charAt(1) + this.eka.substring(2);
muutettu2 += this.eka.charAt(0) + this.eka.charAt(1) + this.toka.substring(2);
System.out.println(muutettu1 + " " + muutettu2);
I'm getting numbers for the .charAt(x) parts, so how do I convert the chars to string?
StringBuilder builder = new StringBuilder();
builder
.append(this.toka.charAt(0))
.append(this.toka.charAt(1))
.append(this.toka.charAt(2))
.append(' ')
.append(this.eka.charAt(0))
.append(this.eka.charAt(1))
.append(this.eka.charAt(2));
System.out.println (builder.toString());
Just use always use substring() instead of charAt()
In this particular case, the values are mutable, consequently, we can use the built in String class method substring() to solve this problem (#see the example below):
Example specific to the OP's use case:
muutettu1 += toka.substring(0,1) + toka.substring(1,2) + eka.substring(2);
muutettu2 += eka.substring(0,1) + eka.substring(1,2) + toka.substring(2);
Concept Example, (i.e Example showing the generalized approach to take when attempting to solve a problem using this concept)
muutettu1 += toka.substring(x,x+1) + toka.substring(y,y+1) + eka.substring(z);
muutettu2 += eka.substring(x,x+1) + eka.substring(y,y+1) + toka.substring(z);
"...Where x,y,z are the variables holding the positions from where to extract."
The obvious conversion method is Character.toString.
A better solution is:
String muutettu1 = toka.substring(0,2) + eka.substring(2);
String muutettu2 = eka.substring(0,2) + toka.substring(2);
You should create a method for this operation as it is redundant.
The string object instatiantiation new String() is unnecessary. When you append something to an empty string the result will be the appended content.
You can also convert an integer into a String representation in two ways: 1) String.valueOf(a) with a denoting an integer 2) Integer.toString(a)
This thing can adding a chars to the end of a string
StringBuilder strBind = new StringBuilder("Abcd");
strBind.append('E');
System.out.println("string = " + str);
//Output => AbcdE
str.append('f');
//Output => AbcdEf

Categories

Resources