Reputation: 16147
My error in my code that even though "A" , "B", "C" exist in the array the if condition inside the inner loop doesn't recognize them. Note that ABC is from a string that has been splitted using the String.split(""); method of java
public class Hexadecimal
{
public static void main(String[] args)
{
String hex = "ABC";
hToD(hex);
}
public static void hToD(String hexa)
{
String[] hexadecimal = {"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"};
String[] value = hexa.split("");
int deci = 0;
int bit =0;
for(int i = 0; i<value.length;i++)
{
for(int j = 0; j<hexadecimal.length;j++)
{
if(value[i] == hexadecimal[j])
{
deci = deci + compute(j,bit++);
System.out.println(deci);
}
}
}
}
public static int compute(int digit,int bit)
{
int ans = 0;
if(bit == 0)
{
ans = digit * (1);
}else
{
ans = digit * (16 * bit);
}
return ans;
}
}
Upvotes: 0
Views: 3516
Reputation: 1008
Try using .equals() instead of == in that inner if statement.
if(value[i].equals(hexadecimal[j]))
Upvotes: 0
Reputation: 692231
Never compare Strings with ==
. Always with s1.equals(s2)
.
The former tests that both objects are the same (i.e. the variables reference the same String object). The latter tests that the sequences of chars of both Strings are the same.
Upvotes: 8