Java checking array contents - java

The problem I am having is using .contains() for an array. This is my current line of code:
if (strings[i].contains(symbol) = true){
strings[] is an array that stores user inputted data, the error message i get for this is "The left-hand side of an assignment must be a variable". I understand what this means, my question is, can I use one string from the array when using .contains() or am I going about this the wrong way?
Any help will be appreciated. Thanks.

The problem is that
strings[i].contains(symbol) = true
is an assignment because of the =. You probably mean
strings[i].contains(symbol) == true
and, because the left hand side is a boolean,
strings[i].contains(symbol)
is already sufficient.

my question is, can I use one string from the array when using .contains()
If you read the Java API for String (http://docs.oracle.com/javase/7/docs/api/java/lang/String.html), contains() is a method from String class.
By knowing that, you can use .contains() on a single String element / a String variable.
String str = "abc";
str.contains(symbol); //This is ok.
String[] strs = {"abc", "def"};
str[0].contains(symbol); //This is ok too.
Both of the above are allowed, because both are String.
String[] strs = {"abc", "def"};
str.contains(symbol); //This is wrong!
One more thing which you should have noted by now in your codes is:
When comparison, use == and not single =
And when comparing strings or objects, use .equals()
Of course, you can also write it as:
if(strings.[i].contains(symbol)) //if this statement is true
if(!strings.[i].contains(symbol)) //if this statement is not true
instead of
if(strings.[i].contains(symbol) == true) //if this statement is true
if(strings.[i].contains(symbol) == false) //if this statement is not true

Related

Java simplyfying a function

I have written a function that checks if a string contains certain words but am not happy with the way the code looks
SO currently i have
private String url = "validator=http://url.com;useraccount=sf4cdamloci;licence=39I8934U401;addedon=343443334;serial=7QW0-5TU8-YN9P-G4FZ;limit=123;days=10"
private String musthave ="validator,useraccount,licence,addedon,serial,limit,days"
So i wanted to check that the url contains the must have words in the string. That eg url must have validator, useraccount, licence.....
SO i have tried the following
Boolean has_validator = false;
Boolean has_licence = false;
.....//others with has_ prefix
String[] split_url = url.split(";")
for(String key_item : split_url){
String[] splitteditem = key_item.split("=");
if (splitteditem[0].equalsIgnoreCase("validator")){
has_validator = true;
}
if (splitteditem[0].equalsIgnoreCase("useraccount")){
has_useraccount = true;
}
....others as well
}
Then later i can easily check
if(has_useraccount && has_...)
The above solution works buts its not scalable as whenever i include a new must have ill have to edit my function.
Is there a better way to achieve this. Am still new to java. I have checked on regex but still i can figure our on how to achieve this.
How do i proceed
Don't use a String to represent a set of Strings. Use... a Set of String: Set<String>. Or at least an array of strings.
Then just use a loop. If any of the word in the set isn't contain in the text, you can immediately return false. If you have never returned false in the loop, then all the words are contained in the text, and you can return true.
Pseudo code:
for each word in the set
if the word is not in the text, return false
end for
return true
If you have a Collection of must-have strings, then you can do something simple like:
mustHave.stream().allMatch(url::contains)
My example isn't doing a case-insensitive check, but you get the idea.

Comparing two Strings using .equals() returns False, but their byte arrays are equal

I'm having some troubles when trying to send an image from a client to a server, because original image is different to the recieved one. In order to find the problem, i'm reading line by line of both image looking for the difference. When I compare the Strings line by line, for some lines using String#equals (e.g. lineo.equals(lined)) result is false, but as they seemed to be the same when I print them in the console, I also compare their byte arrays. Surprisingly, using Array.equals(lineo.getBytes(), lined.getBytes()) result is true. Both client and server are in the same computer.
Please help me to understand
Where can I find the difference between both Strings
Why both methods to compare, returns different results
private void compareImages() throws IOException {
File dest = new File("C:\\TempFiles\\" + fileName);
File orig = new File("C:\\Users\\Andres\\Desktop\\B&N\\" + fileName);
BufferedReader bro = new BufferedReader(new FileReader(orig));
BufferedReader brd = new BufferedReader(new FileReader(dest));
String lineo = bro.readLine();
String lined = brd.readLine();
System.out.println("Ready to read");
while (lineo!= null && lined!= null) {
if(!lined.equals(lineo))
{
System.out.println("lineo");
System.out.println(lineo);
System.out.println("lined");
System.out.println(lined);
System.out.println("arrayo");
System.out.println(printArray(lineo.getBytes()));
System.out.println("arrayd");
System.out.println(printArray(lined.getBytes()));
System.out.println("Are: " + Arrays.equals(lined.getBytes(), lineo.getBytes()));
break;
}
lineo = bro.readLine();
lined = brd.readLine();
}
bro.close();
brd.close();
}
public String strArray(byte[] array){
String toRet = "";
for (byte b : array) {
toRet += b;
}
return toRet;
}
The result of the console was:
lineo
ÿÄ µ }!AQa"q2?‘¡#B±ÁRÑð$3br‚
lined
ÿÄ µ }!AQa"q2?‘¡#B±ÁRÑð$3br‚
arrayo
11-1-600-751602133243554400112512304175183349656198197734113205063-111-9583566-79-632182-47-16365198114-1269
arrayd
11-1-600-751602133243554400112512304175183349656198197734113205063-111-9583566-79-632182-47-16365198114-1269
Are: true
Please, have in mind that I could not copy some characters from the output.
Regards,
Andrés
Unequal strings do not have to produce different arrays when you do getBytes().
The result depends on the platform's default charset, but when I run the following code
String str1 = "?";
byte[] arr1 = str1.getBytes();
String str2 = "\u0080";
byte[] arr2 = str2.getBytes();
System.out.println(str1.equals(str2));
System.out.println(Arrays.equals(arr1, arr2));
the output I see is
false
true
I don't know exactly what is going on here, but it looks like certain control characters get treated as '?'.
The correct way to understand why strings are different is to compare the character arrays returned by toCharArray().
Comparing images using strings might not be the best way to about it.
Compare their byte (Use ByteArrayInputStream).
The strings' return character could be different or there might be some encoding differences between them.
Strings are funny things. Strings are immutable. If you create two strings with the same value they both point to the same reference in memory. This is called interning. If you update one of those strings we get a new value in memory and the pointer of your variable points to the new value.
When you create your two strings you're assigning different values to them, it doesn't care if one is encoded and the other isn't, it doesn't actually know the difference at this point. You therefore have two string variables pointing to different values. When you do a .equals() you're checking the equivalency of the two string objects (do they point to the same thing; no they do not; therefore false).
Here's a good article from Microsoft that explains it better than I can.

Checking a number in String Variable [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I am getting a value as 9999912499 from the database.
I have separated it in two parts 99999 and 12499 using substring.
Now I want to check whether if the 1st string is equal to 99999 then i do some processing otherwise something other processing.
But controls never gets in to the if loop
Following is a snapshot:
String strPscId = Long.toString(pscID);
String convPscID = strPscId.substring(5, strPscId.length());
String checkNine = strPscId.substring(0,5);
BigDecimal jpaIdObj = jeuParam.getJpaIdObj();
Long mod_id = modele.getModId();
log.info("outstrPscId == " +strPscId);
log.info("outconvPscID == " +convPscID);
log.info("outcheckNine == " +checkNine);
log.info("outjpaIdObj == " +jpaIdObj);
log.info("outmod_id == " +mod_id);
if(checkNine == "99999") { <method-call> }
else { <another - method - call> }
For some reason, the people that make java decided that == shouldn't be used to compare Strings, so you have to use
checkNine.equals("99999");
Look at the following code:
String str1 = "abc";
String str2 = str1;
In the first line, a new string is created and stored in your computer's memory. str1 itself is not that string, but a reference to that string. In the second line, str2 is set to equal str1. str2 is, like str1, only a reference to a place in memory. However, rather than creating an entirely new string, str2 is a reference to the same place in memory that str1 is a reference to. == checks if the references are the same, but .equals() checks if the each character in a string is the same as the corresponding character in the other string.
boolean bool1 = (str1 == str2);
boolean bool2 = str1.equals(str2);
If this code were added to the code above that, both bool1 and bool2 would be true.
String str1 = "abc";
String str2 = new String(str1);
boolean bool1 = (str1 == str2);
boolean bool2 = str1.equals(str2);
In this case bool2 is still true, but bool1 is false. This is because str2 isn't set to equal str1, so it isn't a reference to the same place in memory that str1 is a reference to. Instead, new String(str1) creates an entirely new string that has the value of str1. str1 and str2 are references to two different places in memory. They contain the same value, but are fundamentally different in that they are stored in two different places, and therefore are two different things.
If I replaced new String(str1) with "abc" or str1, bool1 would be true, because without the key word new, the JVM only creates a new string to store in memory if absolutely necessary. new forces the JVM to create an entirely new string, whether or not any place in memory already has the same value as the new string being created.
.equals() is slow but generally more useful than ==, which is far faster but often does not always give the desired result. There are many times when == can be used with the same result as .equals(), but it can be difficult to tell when those times are. Unless you a knowledgeable programmer making something where speed is important, I would suggest that you always use .equals().
You need use equals method, rather than == to compare strings.
Change from
if(checkNine == "99999")
to
if(checkNine.equals("99999"))
The == operator is used to compare the content of two variables. This works as expected when using primitive types (or even wrapper classes because of auto-boxing). However, when we are using == with a reference to an object (e.g., checkNine), the content is the reference to the object but not the value of the object. This is where equals() method is used.
if("99999".equals(checkNine)){
<method-call>
}
else {
<another - method - call>
}
if(checkNine.equals( "99999")) {
<method-call>
}
else {
<another - method - call>
}
if (strPscId.startsWith("99999"))
{
bla bla
}
else
{
sth else than bla bla
}

what happens when converting char to string? (Java) [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I compare strings in Java?
I'm using String.valueOf to convert char to string. But the return value seems not exactly same as a string of the same letter. Codes below:
String myString = "s";
char myChar = 's';//both string and char are assigned as letter 's'
String stringFromChar = String.valueOf(myChar);
if (myString == stringFromChar) {
out.println("equal");
} else {
out.println("not equal");
}
Every time it prints not equal. Please help, thanks! :)
== compare the reference, not the actual value. You must use equals to compare the value.
Read this article if you don't understand it's clear and simple.
NEVER DO THIS AGAIN!!! PROMISE ME!!! =P
When comparing strings always, always, always use the equals method. See Below!
String myString = "s";
char myChar = 's';//both string and char are assigned as letter 's'
String stringFromChar = String.valueOf(myChar);
if (myString.equals(stringFromChar)) {
System.out.println("equal");
} else {
System.out.println("not equal");
}
}
what happens when converting char to string?
Well, you are using the String.valueOf(char) method, whose javadoc does not say how it does the conversion. But the behaviour you are seeing strongly suggests that the JVM you are using creates a new String object each time you call the method.
But you should depend on this happening.
The bottom line is that you should always use the equals method to compare strings. Comparing strings with == will often give you false negatives ... depending on how the strings were created / obtained. You've just been bitten by that. Learn.
Reference:
How do I compare strings in Java?

Using String.endswith() method on Java

I have an array I want to check the the last digits if it is in the array.
Example:
String[] types = {".png",".jpg",".gif"}
String image = "beauty.jpg";
// Note that this is wrong. The parameter required is a string not an array.
Boolean true = image.endswith(types);
Please note:
I know I can check each individual item using a for loop.
I want to know if there is a more efficient way of doing this. Reason being is that image string is already on a loop on a constant change.
Arrays.asList(types).contains(image.substring(image.lastIndexOf('.') + 1))
You can substring the last 4 characters:
String ext = image.substring(image.length - 4, image.length);
and then use a HashMap or some other search implementation to see if it is in your list of approved file extensions.
if(fileExtensionMap.containsKey(ext)) {
Use Arrays.asList to convert to a List. Then you can check for membership.
String[] types = {".png",".jpg",".gif"};
String image = "beauty.jpg";
if (image.contains("."))
System.out.println(Arrays.asList(types).contains(
image.substring(image.lastIndexOf('.'), image.length())));

Categories

Resources