String comparison is wrong [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I have a little/huge problem with String comparison in Java, I want to compare two Strings and .equals([...]) does not give me the correct result.
I also tried the following: ==, .compareTo([...]), .trim(), .equalsIgnoreCase([...]), creating a Collator with default Locale and using [collator].compare.
(All fail to work)
The first String comes from an already created object (the content of the string is from a database), the second String comes from a newly created object (but has been passed to a method), the content of this String is from the same database.
I am pretty clueless what to do now, the last thing I'd try is to convert it to some number (i.e. hex).
I already tried to write both Strings to console and manually look for differences, but there is none...
Code is this:
public static Lagerplatz hinzufuegen(Lagerplatz lagerplatz) {
boolean neu = true;
if (lagerplaetze.isEmpty()) {
lagerplaetze.add(lagerplatz);
System.out.println(lagerplatz.getBezeichnung() + " erstmalig hinzugefügt!");
}
for (int i = 0; i < lagerplaetze.size(); i++) {
System.out.println("'" + lagerplatz.getBezeichnung() + "'" + " - " + "'"
+ lagerplaetze.get(i).getBezeichnung() + "'");
if (lagerplatz.getBezeichnung().equalsIgnoreCase(lagerplaetze.get(i).getBezeichnung())) {
neu = false;
}
}
if (neu) {
lagerplaetze.add(lagerplatz);
System.out.println(lagerplatz.getBezeichnung() + " hinzugefügt!");
}
return lagerplatz;
}
The if-part with (lagerplaetze.isEmpty()) does work, after the first one is added it should check if the Lagerplatz (at least the name of it) is already in the lagerplaetze-ArrayList, if so then don't add, if not add.
Stepping through it revealed that the objects are correctly referenced...
Thanks very much in advance, and sorry if this question has been answered already but I can't find a helping answer under all these questions...
EDIT1: Normalizing does not help in this case, "umlaute" (german ä, ö or ü) are not causing the problem...
Converting the String to a byte[] and converting this byte-array to String like:
(Arrays.toString(lagerplatz.getBezeichnung().getBytes()).equalsIgnoreCase(
Arrays.toString(lagerplaetze.get(i).getBezeichnung().getBytes())))
and then comparing it does also not solve the problem, the bytes of the two strings are exactly the same: '[72, 55, 48]' - '[72, 55, 48]'
EDIT2: The problem is not with the String comparison, it is because the variables of the class "Lagerplatz" are static, they were replaced each time the loop is entered...
Maybe delete this question?

The only time two strings that look exactly the same but equals() does not result in true is when the unicode composition is different.
For example one can compose the A umlaut (Ä) with a single character: \u00C4
Or with a combination of the A character and the dots (the dieresis character ¨): \u0041\u0308
In essence, you are using two unicode characters for one letter. Because equals() compares characters, the form with dieresis is not equals to the form without.
To overcome this problem, one must decompose each string to a canonical form before comparison.
In Java one can create such a canonical form like this:
java.text.Normalizer.normalize("Your String", java.text.Normalizer.Form.NFD);
Once normalized, equals() will work as expected.
Obviously, since you didn't provide any data, this answer may or may not match your problem.
In any case, you might want to normalize all Strings in some form and then use a Set as data structure, not a list.

Related

Search a string array for a specific string. [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I was hoping someone could help. Well I know how to use linear search to find a numerical value inside of an array. But now I want to learn how to search a string array for a string.
For example if I have a string array of students names how could I search the array to find a specific name inside that array?
If someone could write me a simple example since I'm new to Java still. Thank you, also is there a better way to search these kinds of things or linear search fine? :)
Use Arrays.asList() to wrap the array in a List. Then search in the List using contains() method:
String[] a= {"is", "are", "then"};
Arrays.asList(a).contains("are");
You can do using arrays also, but have to write some more lines of code. contains() method also does the linear search only.
public static boolean useLoop(String[] arr, String targetValue) {
for(String s: arr){
if(s.equals(targetValue))
return true;
}
return false;
}
The code for Strings can be the same as for numerical values, except you should use the String class's equals(...) method instead of ==.
You should use equals(...) because it's possible for two different String objects to have the same characters. But == would be incorrect because they are different objects.
Examples comparison expressions:
myArray[i].equals(myString)
or
myString.equals(myArray[i])
Note: Be sure the part on the left side isn't null. Otherwise you will get a NullPointerException.

Object created while using String methods in java [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
public class StringDemo
{
public static void main(String [] args)
{
String s = "Sachin";
s.concat(" Tendulkar");
s.toLowerCase();
System.out.print(s);
}
}
This example giving output as : Sachin
then how many objects have been created?
The answer is: an indeterminate number.
on the face of it, the two operations on s each create a single String object,
two more String objects are created at load time to represent the literals,
objects may be created when print is called: internally to the System.out PrintWriter and the stream stack that it wraps,
each String object may (or may not) have a distinct char[] object inside it,
it is possible that the operations on s could be optimized away, since they actually have no effect on the output of the program (!!),
when the application is called, it will be passed a String[] argument, potentially populated with multiple String, and (finally),
an arbitrary number of objects will be created during JVM bootstrapping and class loading ... prior to the application starting.
So, depending on what objects you count, how you count them, and the other assumptions that you make, the answer could be some number from zero to a very large number of objects.
Note: the normal quiz answer for this would be "2 Strings are created", but as you can see the answer is a lot more complicated than that.
Note 2: the concat and toLowerCase methods do NOT create strings in the string pool. In fact, the only String operation that puts strings into the pool is intern. (It is easy to verify this experimentally, or by reading the Java class library source code.)
String in java is a immutable type.
s.concat(" Tendulkar");
s.toLowerCase();
these 2 lines return 2 distinct strings and doesn't affect the original string.
In java String is considered as immutable which means that it cannot be changed once its created, so if you count how many you have, on the first line you declared the first one, when you did s.concat("SE 6") you created a new object, and finally s.toLowerCase() created the 3rd object, therefore 3 string objects are created.

stringoutofboundexception in java (due to long string) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am getting a StringIndexOutOfBoundsException for a long string. Basically the program is reading string from text file and for some reason i am getting error when I use long strings. For e.g. if use a=b+c or a=b or a=b+c-d*a this all works but when i put long strings such as "programming" or "javatutorial" this gives me a StringIndexOutOfBoundsException. At first I thought this was due to the fact that I am not checking whether or not x is empty but that is not the case this is occurring due to the length of the string itself. I would appreciate if someone could help.
while (scan.hasNext()) {
String x = scan.nextLine();
try
{
if(!x.isEmpty())
{
char ch=x.charAt(0);
s=String.valueOf(ch);
}
}
catch(StringIndexOutOfBoundsException siobe)
{
System.out.println("invalid input");
}
}
With the partial code you provided, all we can tell you is that the exception is being thrown because you are using the method:
String.charAt(int index)
on a String that does not have a character at the 'index'-th position.
For example, if String word = "cat", then word.charAt(8) would throw an exception because 'cat' only has three characters.
Search through your code for all the places that you used the charAt(int index) method and test that 'index' is indeed less than String.length(). Your error shows an argument of '11', so you can narrow your search to the location where you called the charAt() method with an index of 11. (This may be inside a loop).

Handling Invalid Character Constant [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have been working on a data compression and decompression program in java. At some point in my code, I want to visit only the nodes with keys. The part of the code looks like this:
//visit only nodes with keys
if(n.alpha != '\0') {
System.out.println("{" + n.alpha + ":" + s + "}");
charToCode.put(n.alpha, s);
codeToChar.put(s, n.alpha);
}
'\0' gives me an invalid character constant. I need to know what is going on, and how I can remedy the situation. Thanks!
You're trying to represent and treat a String as a char
n.alpha != '\0' // single quotes denote a character
You need to use a String instead
n.alpha != "\0"
Then, because the equality operator generally shouldn't be used with Strings, and because you're incorrectly testing the equality between a String and a char, you need to rewrite it as
if(!Character.toString(n.alpha).equals("\0"))
Note the use of Character.toString(n.alpha) to convert the char n.alpha to a String.

How to check if File "mm" exists in uppercase like "mM" or "Mm" in linux [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
so how may I check that? There are 36'000 files and on every event call I would need to check it, there could be plenty of these situations like: "nukasa" or "Nukasa" or "nUkasa", how may I detect all of these if I have one file name like: "NUKASA" or "nukasa" by event calling.
It's work with File not String. I just get String and then I need to work with File to check if in folder exists same file names just in Uppercase or Lowercase.
Please refer below the snippet I want to show as an example:
File sampleFile = new File("Nukasa");
String valueToCheck = "NUKASA";
if(sampleFile.getName().equalsIgnoreCase(valueToCheck))
{
//Logic you want to code goes here
}
Alternatively, you can use file.getName().toUpperCase().equals(valueToCheck) (if you assign upper case string to the variable valueToCheck). Same applies to toLowerCase() method also
CAUTION: This approach works fine as long as the Locale is of English language. For other languages, it won't work as expected. So, equalsIgnoreCase() is the best way. Credits to the person who suggested this
For case insensitive string comparison, use the String method str1.equalsIgnoreCase(str2).

Categories