# Scanner for hex-input not working as expected inside loop

I need to solve this problem where i need to convert hexadecimal numbers to decimals.

### Issue

I have compiled it without any errors, but my output came out wrong. Can someone show how to fix these errors?

## Code

```import java.util.Scanner;
import java.io.*;
class HexToDecException extends Exception  {

public HexToDecException(String msg) {
super(msg);
}
}

public class Main {
public static int hexToDec(String hex) throws HexToDecException {
char currentChar;
int dec=0;
int power = 0;

for(int i=hex.length()+1;i>=0;i--){// by reverse
currentChar = hex.charAt(i);

if(currentChar>='0' && currentChar<='9'){
dec+= Math.pow(16,power)*(currentChar - '0');
power++;
}
else if(currentChar>='a' && currentChar<='f'){
dec+= Math.pow(16,power)*(currentChar - 'a' + 10);
power++;
}
else if(currentChar>='A' && currentChar<='G'){
dec+= Math.pow(16,power)*(currentChar - 'A' + 10);
power++;
}
else
throw new IllegalArgumentException("Invalid Character in Hexadecimal string");
}

return power;
}
public static void main(String[] args){
Scanner scan = null;
try{
scan = new Scanner(System.in);
int n = scan.nextInt();
for(int i=0;i<n;i++)
System.out.println(hexToDec(scan.next()));
}
catch(Exception ex){
ex.printStackTrace();
}

finally{
System.out.println("That's all.");
}
}
}
```

### Example

Input:

```5 6B 5 4AZ A5 9
```

Expected Output:

```107  5 Invalid hexadecimal number 165 9
```

Output that i got:

```That's all
```

Your solution is close. Here are changes to make so that it runs correctly:

• modify the `return` statement of `hexToDec()` to return the decimal number you’ve constructed, not the power, so change this: `return power` to this: `return dec`
• modify `throws` clause to this: `throw new HexToDecException("Invalid hexadecimal number");` – use the custom exception you defined, and edit the string message to match the output you’re expecting
• change the `for` loop in `hexToDec()` so it that properly checks each position in the input string, so change this: `for (int i = hex.length() + 1` to this: `for (int i = hex.length() - 1`. Maybe read up on how `String.length()` works in relation to `charAt()`. If a string has a length N, the corresponding “Nth” position in that string has to be referenced by N-1. N itself would never work, and N+1 would also not work.
• finally, rewrite the main loop to wrap the call to `hexToDec()` in a `try-catch`, and print the exception message if an exception is thrown:
```Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
for (int i = 0; i < n; i++) {
String nextInput = scan.next();
try {
int x = hexToDec(nextInput);
System.out.print(x + " ");
} catch (HexToDecException e) {
System.out.print(e.getMessage() + " ");
}
}
```

After those changes, this input:

```5 6B 5 4AZ A5 9
```

will produce this output:

```107 5 Invalid hexadecimal number 165 9
```
User contributions licensed under: CC BY-SA
7 People found this is helpful