Question:
(java programming) my code doesnt convert from hexidecimal to decimal!! why?
Dmitri
2010-06-29 08:57:49 UTC
import java.io.*;
class Exx2
{
public static void main(String[] args)
{
Console console=System.console();
System.out.println("please type a hexadecimal number");
String input;
input=console.readLine();
char c= input.charAt(0);
int count=0;
int number2=0;
String abc= "abcdef";

char NewC;
NewC='5';

if(c==c)
{
while(c==abc.charAt(count))
{
number2=9+count;
count++;
System.out.println(number2);
}

}
else
{
System.out.println(input);
}

}
}


if i write "a" it should look for it in the while loop till it finds it,, but all that process doesnt happen , why?
Three answers:
?
2010-06-29 09:36:53 UTC
I think the other answer points out the problems with your code, all I'm going to offer is another method of doing the same process:



String hex = "0123456789abcdef";

int dec = hex.indexOf(c);

System.out.println("decimal=" + dec);



If the value returned is -1, from the second line, then the entered char isn't a valid one ( -1 is returned from indexOf when it can't find the character you want to find ).
Archana
2010-06-29 09:17:27 UTC
You have made quite a few mistakes in your logic

First of all, what is the point of having c==c? It will always return true



Secondly, in your while loop

while(c==abc.charAt(count))



only if user enters 'a', the condition will be true and the count will be incremented.

So, if user enters anything other than 'a'. The loop will not execute and you wont get the desired output



What you need to do is:

1. Set up a loop to iterate though the entire string abc

2. Check if the entered character is equal to the character in abc

3. If so add 9 and exit the loop







while(count < abc.length())

{

if(c==abc.charAt(count))

{

number2=9+count;



System.out.println(number2);

break;

}

else

{

System.out.println(input);

}

count++;

}
2010-06-29 09:31:45 UTC
... or you could not recreate the wheel and use already existing methods.



String hexString = "abcdef";

int value = Integer.parseInt(hexString,16);



System.out.println(value); // 11259375 in base 10


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...