# hex conversion...

At line:

try{

if (ch<'0' || ch>'F')
throw new NumberFormatException("not a hex number.");
.
.

When ch is G, it doesn't throw "not a hex number." error?

Q1: 'G' > 'F', why then this doesn't work.
Q2: What happens if the data supplied is lower case? like g in place of G or b in place of B?

Thank you.
``````import java.util.Scanner;

public class Exercise13_6{

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

System.out.print("Enter a hex number: ");
String hex=input.nextLine();

System.out.println("The decimal value for hex number "
+ hex + " is " + hexToDecimal(hex.toUpperCase()));
}

public static int hexToDecimal(String hex) {
int decimalValue=0;
for(int i=0; i<hex.length();i++) {
char hexChar=hex.charAt(i);
decimalValue=decimalValue*16+hexToDecimal(hexChar);
}
return decimalValue;
}

public static int hexToDecimal(char ch)  {

int temp=0;
try{

if (ch<'0' || ch>'F')
throw new NumberFormatException("not a hex number.");

if (ch>='A' && ch <='F')
temp = 10+ch-'A';
else
temp = ch-'0';

}catch (NumberFormatException ex){
//                         ex.printStackTrace();

}
return temp;
}
}
``````
Java

Last Comment
CEHJ
for_yan

This works for me:

`````` char    cc = 'G';

if(cc < '0' || cc > 'F')   System.out.println("bigger");
``````
for_yan

There is a method hex to int you don't need to write it
for_yan

That is becaiue you have additional catch loop there
for_yan

`````` public static int hexToDecimal(char ch) throws NumberFormatException {

int temp=0;

if (ch<'0' || ch>'F')
throw new NumberFormatException("not a hex number.");

if (ch>='A' && ch <='F')
temp = 10+ch-'A';
else
temp = ch-'0';

return temp;
}
``````
for_yan

You were catching it in the additional catch loop and even not printing the stackTrace - so uyou just caught the exception and
didn't inform anyoje about it - and you didn't see that it was throwing it - the above post should work
for_yan

That's how it works:

``````public class TryHexToDecimal {
public static int hexToDecimal(char ch) throws NumberFormatException {

int temp=0;

if (ch<'0' || ch>'F')
throw new NumberFormatException("not a hex number.");

if (ch>='A' && ch <='F')
temp = 10+ch-'A';
else
temp = ch-'0';

return temp;
}

public static void main(String[] args) {

System.out.println(hexToDecimal('G'));

}
}
``````

``````Exception in thread "main" java.lang.NumberFormatException: not a hex number.
at Miscellaneous.hexToDecimal(Miscellaneous.java:24)
at Miscellaneous.main(Miscellaneous.java:39)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:110)
``````
for_yan

lowercase is bigger than upper case
so

'a' > 'F'

so it will cause exception also

so you want to do something like that:
``````   boolean good = false;
if((ch >= '0' && ch <= 'F')  || (ch >= 'a' && ch <= 'f'))good = true;

if (!good)
throw new NumberFormatException("not a hex number.");
``````

But then you should take care of another oart where uyou
should assign values to a-f lowere case

Instead of doing all that just use the method
which makes int out of hex string which I posted above

for_yan

and maybe even better method:

int i = Integer.parseInt(String s, int radix)

for_yan

This is how it parseInt() method works:

``````    int inum = Integer.parseInt("12Fc10",16);

System.out.println("inum: " + inum);

``````

Output:
``````inum: 1244176
``````

``````          int inum1 = Integer.parseInt("12Fc10g",16);
``````

Output:

``````Exception in thread "main" java.lang.NumberFormatException: For input string: "12Fc10g"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:458)
at Miscellaneous.main(Miscellaneous.java:47)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:110)
``````
Mike Eghtebas

On the original issue, I am getting error message like:

Enter a hex number: k
Exception in thread "main" java.lang.NumberFormatException: K is not a hex number.
at Exercise13_6.hexToDecimal(Exercise13_6.java:31)
at Exercise13_6.hexToDecimal(Exercise13_6.java:21)
at Exercise13_6.main(Exercise13_6.java:13)
Java Result: 1
BUILD SUCCESSFUL (total time: 4 seconds)

Where I just want:

K is not a hex
``````import java.util.Scanner;

public class Exercise13_6{

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

System.out.print("Enter a hex number: ");
String hex=input.nextLine();

System.out.println("The decimal value for hex number "
+ hex + " is " + hexToDecimal(hex.toUpperCase()));
}

public static int hexToDecimal(String hex) {
int decimalValue=0;
for(int i=0; i<hex.length();i++) {
char hexChar=hex.charAt(i);
decimalValue=decimalValue*16+hexToDecimal(hexChar);
}
return decimalValue;
}

//    public static int hexToDecimal(char ch)  {
public static int hexToDecimal(char ch) throws NumberFormatException {
int temp=0;

if (ch<'0' || ch>'F')
throw new NumberFormatException(ch + " is not a hex number.");

if (ch>='A' && ch <='F')
temp = 10+ch-'A';
else
temp = ch-'0';

return temp;

}
}
``````
for_yan

You need to define your own custom Exception and
after you catcgh NumberFormat throw your Custom exception - look
at our previous exrcises  where you were doing calculator

for_yan

Or you can do it like that - catch it
but not print the exception with toString() or with ex.printStackTrace()
but rather print your own message:

`````` public static int hexToDecimal(char ch)  {

int temp=0;

try{
boolean good = false;
if((ch >= '0' && ch <= 'F')  || (ch >= 'a' && ch <= 'f'))good = true;

if (!good)
throw new NumberFormatException("not a hex number.");

if (ch>='A' && ch <='F')
temp = 10+ch-'A';
else
temp = ch-'0';

} catch(Exception ex){
System.out.println("Not a hex");

}

return temp;
}
``````
Mike Eghtebas

Thanks I guess I can handle this.
for_yan

Say, like that:

``````pubblic class HandlingExcept {
public static int hexToDecimal(char ch)  {

int temp=0;

try{
boolean good = false;
if((ch >= '0' && ch <= 'F')  || (ch >= 'a' && ch <= 'f'))good = true;

if (!good)
throw new NumberFormatException("not a hex number.");

if (ch>='A' && ch <='F')
temp = 10+ch-'A';
else
temp = ch-'0';

} catch(Exception ex){
System.out.println(ch + " is not a hex character");

}

return temp;
}

public static void main(String[] args) {

System.out.println(hexToDecimal('g'));
}
}
``````

``````g is not a hex character
``````
Mike Eghtebas

This is what I have so far, but it has one error:
``````import java.util.Scanner;

public class Exercise13_6{

public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a hex number: ");
String hex=input.nextLine();
System.out.println("The decimal value for hex number "
+ hex + " is " + hexToDecimal(hex.toUpperCase()));
}

public static int hexToDecimal(String hex) {
int decimalValue=0;
for(int i=0; i<hex.length();i++) {
char hexChar=hex.charAt(i);
decimalValue=decimalValue*16+hexToDecimal(hexChar);
}
return decimalValue;
}

public static int hexToDecimal(char ch) throws
InvalidDataException13_6, NumberFormatException {
int temp=0;
boolean good = false;

try{
if((ch >= '0' && ch <= 'F')  ||
(ch >= 'a' && ch <= 'f'))good = true;

if (!good) //{
throw new InvalidDataException13_6(ch+" is not a hex number.");
//               }else{
if (ch>='A' && ch <='F')
temp = 10+ch-'A';
else
temp = ch-'0';
//               }
} catch(Exception ex){
//            System.out.println("Not a hex");
throw new InvalidDataException13_6 (ch+" is not a hex number.");
}
return temp;
}
}

class InvalidDataException13_6 extends Exception {
private String mistake;
public  InvalidDataException13_6(String err)
{
super(err);     // call super class constructor
mistake = err;  // save message
}

public String toString(){
return mistake;
}
}
``````
Mike Eghtebas

I guess I have it now
``````import java.util.Scanner;

public class Exercise13_6{

public static void main(String[] args) throws
InvalidDataException13_6, NumberFormatException {
Scanner input = new Scanner(System.in);
System.out.print("Enter a hex number: ");
String hex=input.nextLine();
System.out.println("The decimal value for hex number "
+ hex + " is " + hexToDecimal(hex.toUpperCase()));
}

public static int hexToDecimal(String hex) throws
InvalidDataException13_6, NumberFormatException {
int decimalValue=0;
for(int i=0; i<hex.length();i++) {
char hexChar=hex.charAt(i);
decimalValue=decimalValue*16+hexToDecimal(hexChar);
}
return decimalValue;
}

public static int hexToDecimal(char ch) throws
InvalidDataException13_6, NumberFormatException {
int temp=0;
try{
if((ch >= '0' && ch <= 'F')  || (ch >= 'a' && ch <= 'f'))//good = true;
throw new InvalidDataException13_6(ch+" is not a hex number.");
if (ch>='A' && ch <='F')
temp = 10+ch-'A';
else
temp = ch-'0';
} catch(Exception ex){
throw new InvalidDataException13_6 (ch+" is not a hex number.");
}
return temp;
}
}

class InvalidDataException13_6 extends Exception {
private String mistake;
public  InvalidDataException13_6(String err)
{
super(err);     // call super class constructor
mistake = err;  // save message
}

public String toString(){
return mistake;
}
}
``````
Mike Eghtebas

not quite there yet.
for_yan

Seems OK, but I'm not sure if it will be lower case, this part will work correctly:

if (ch>='A' && ch <='F')
temp = 10+ch-'A';
else
temp = ch-'0';

and if ch = 'b' - ?
CEHJ

>>
if (((ch >= '0') && (ch <= 'F')) || ((ch >= 'a') && (ch <= 'f'))) { //good = true;
throw new InvalidDataException13_6(ch +
" is not a hex number.");
}
>>

Your logic is the wrong way around there
Mike Eghtebas

I ran for k, this is whay I got:

run:
Enter a hex number: k
The decimal value for hex number k is 27
BUILD SUCCESSFUL (total time: 5 seconds)

which is wrong result.  and:

Enter a hex number: A22
Exception in thread "main" A is not a hex number.
at Exercise13_6.hexToDecimal(Exercise13_6.java:35)
at Exercise13_6.hexToDecimal(Exercise13_6.java:19)
at Exercise13_6.main(Exercise13_6.java:10)
Java Result: 1
BUILD SUCCESSFUL (total time: 7 seconds)

Mike Eghtebas

re:> Your logic is the wrong way around there

I will revise and test it again
for_yan

Use this logic :

``````  boolean good = false;
if((ch >= '0' && ch <= 'F')  || (ch >= 'a' && ch <= 'f'))good = true;

if (!good)
throw new NumberFormatException("not a hex number.");
``````

but rervise the part where you calculate the actuall value form lower case - it should be sdifferent
Mike Eghtebas

OK
for_yan

I think this should work:

``````  public static int hexToDecimal(char ch)  {

int temp=0;

try{
boolean good = false;
if((ch >= '0' && ch <= 'F')  || (ch >= 'a' && ch <= 'f'))good = true;

if (!good)
throw new NumberFormatException("not a hex number.");

if (Character.toUpperCase(ch)>='A' && Character.toUpperCase(ch)<='F')
temp = 10+Character.toUpperCase(ch)-'A';
else
temp = Character.toUpperCase(ch)-'0';

} catch(Exception ex){
System.out.println(ch + " is not a hex character");

}

return temp;
}
``````
for_yan

Or just convert your character to upper case form the very nebgging and that will make your code
mauch easier (baseically like it was in the beginning)
CEHJ

>>  if((ch >= '0' && ch <= 'F')  || (ch >= 'a' && ch <= 'f'))good = true;

Won't work unfortunately - it will set good to true for '@'

You'd be better off with
``````ch = Character.toLowerCase(ch);
good = "0123456789abcdef".indexOf(ch) > -1;
``````
for_yan

THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
CEHJ

>>if (Character.toUpperCase(ch)>='A' && Character.toUpperCase(ch)<='F')

Don't do that. Convert it straight away and call the method once, not multiple times
for_yan

Well, in the end use, parseInt as I mentioned above - this is definitely something wahich you sdon't want to write yourself
SOLUTION
CEHJ

THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
CEHJ

>>this is definitely something wahich you sdon't want to write yourself

Well i think that goes without saying, outside an academic exercise, which is what i assume this is
CEHJ

>>I think this should also work:

It doesn't - for the reason i gave at http:#:36945129

Can you tell me why you accepted an incorrect answer eghtebas?
Java

Java is a platform-independent, object-oriented programming language and run-time environment, designed to have as few implementation dependencies as possible such that developers can write one set of code across all platforms using libraries. Most devices will not run Java natively, and require a run-time component to be installed in order to execute a Java program.

102K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts

TRUSTED BY