Reputation: 834
I've the below code.
import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
public class Dummy {
public static void main(String args[]) throws Exception {
String word="hi";
String[] one={"a","b","c"};
String[] two={"d","e","f"};
String[] three={"g","h","i"};
String[] four={"j","k","l"};
String[] five={"m","n","o"};
String[] six={"p","q","r","s"};
String[] seven={"t","u","v"};
String[] eight={"w","x","y","z"};
for(int i=0;i<word.length();i++)
{
for(int j=0;j<three.length;j++)
{
if(three[j].equals(word.charAt(i)))
{
System.out.println("Matched");
}
else
{
System.out.println("err");
}
}
}
}
}
Here my concept is to match a letter from the string to the array created and here the output is all err(condition stating not matched). please let me know where am i going wrong.
Thanks
Upvotes: 0
Views: 87
Reputation: 769
Just saying the obvious....sometimes it is helpful to see the actual code. Following is excerpt from java.lang.String
See bold condition in particular. it returns false if instanceof fails!
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (**anObject instanceof String**) {
String anotherString = (String)anObject;
int n = count;
if (n == anotherString.count) {
char v1[] = value;
char v2[] = anotherString.value;
int i = offset;
int j = anotherString.offset;
while (n-- != 0) {
if (v1[i++] != v2[j++])
return false;
}
return true;
}
}
return false;
}
Upvotes: 0
Reputation: 1661
The element three[j] in for loop is String whereas word.charAt(i) is char.. so equals() against those will be always false.
You should either change it to
if(three[j].equals(String.valueOf(word.charAt(i))))
so that it compares string's actual context, or define arrays (one, two, three.. ) to be char array instead of string array so that you can simply use == for that.
Please check equals() for String, Object, and the others in JavaDoc, and probably you need to check hashCode() as well to fully understand what's equals() means in Java.
Upvotes: 1
Reputation: 759
Try like this:
StringBuffer result = new StringBuffer();
for (int i = 0; i < one.length; i++) {
result.append(one[i]);
}
if (result.toString().equals(word)) {
System.out.println("Matched");
} else {
System.out.println("err");
}
Upvotes: 0
Reputation: 24276
Why don't you use String.indexOf() ?
for(int j=0;j<three.length;j++)
{
if(word.indexOf(three[j]) == -1)
{
System.out.println("err");
}
else
{
System.out.println("Matched");
}
}
This way you will enter in a single loop..
Upvotes: 0
Reputation: 76
charAt return a char not a string so it can't be "equals" to a String
Upvotes: 0
Reputation: 41474
You're comparing a single-character string (from your arrays) to a character. Make your arrays of char
, not String
. (And use ==
to compare them.)
Upvotes: 3