-1

I need to convert hexadecimal to decimal using different methods. When I enter numbers that are correct hexadecimal numbers, my program displays the decimal value and says that the number is valid. However, when I enter incorrect hexadecimal values, my program crashes. Here is my code:

import java.io.*;

import java.util.Scanner;

public class pg3a {

 public static void main(String[] args)  throws IOException {

   Scanner keyboard = new Scanner(System.in);

     String hex;
     char choice = 'y';
     boolean isValid = false;
  do {
     System.out.print("Do you want to enter a hexadecimal number? ");
     System.out.print("y or n?: ");
     choice = keyboard.next().charAt(0);
 switch(choice){
    case 'y':
      System.out.print("Enter a hexadecimal number: #");
      hex = keyboard.next();
      hex = hex.toUpperCase();
      int hexLength = hex.length();
      isValid = valid(hex);
      Integer value = Integer.parseInt(hex,16);
      System.out.println("The value: " + value);

   if (isValid) {
      System.out.println(hex + " is valid");
  }
   break;
  case 'n':
      System.out.print("Quit");
  }
  }while (choice != 'n');
  }

public static boolean valid (String validString) {

  int a = 0;
  if (validString.charAt(0) == '-') {
  a = 1;
  }
    for (int i=a; i< validString.length(); i++) {
       if (!((validString.charAt(i) >= 'A' && validString.charAt(i) <= 'F')|| (validString.charAt(i) >= 0 && validString.charAt(i) <= 9)))
   {
   return false;
   }
   }
   return true;
   }


  public static long convert (String hexValue) {

    long decimal = 0;
    boolean isNegative = false;
    int a = 0;

    if (hexValue.charAt(0) == '-') {
    isNegative = true;
    a = 1;
   }
   for (int i = a; i<hexValue.length(); i++) {
      decimal = decimal*16;
        if (hexValue.charAt(i) >= '0' && hexValue.charAt(i) <= '9') {
        decimal += hexValue.charAt(i) - '0';
     }
       else if (hexValue.charAt(i) >= 'a' && hexValue.charAt(i) <= 'f') {
          decimal += hexValue.charAt(i) - 'a' + 10;
     }
     }
       if (isNegative == true) {
         decimal *= -1;
    }
    return decimal;
    }
    }

why is it crashing and how can I fix it so that it displays "invalid" when incorrect hexadecimal digits are entered?

Kara
  • 6,115
  • 16
  • 50
  • 57

4 Answers4

1

If you enter an invalid hex number, Integer.parseInt() will throw NumberFormatException. Change your code like this:

...
isValid = valid(hex);

if (isValid) {
    Integer value = Integer.parseInt(hex,16);
    System.out.println("The value: " + value);
    System.out.println(hex + " is valid");
}
...
Axel
  • 13,939
  • 5
  • 50
  • 79
  • When I do this, the program doesn't crash anymore (so thank you!!!) but now when I enter a valid hex number, it shows up with "invalid" instead of the value. Any idea why? – user2805867 Oct 02 '13 at 06:44
  • Check your `valid()` method. – Axel Oct 02 '13 at 09:52
0

Add Integer value = Integer.parseInt(hex,16); inside if statement and print invalid in else block.

 if (isValid) {
       Integer value = Integer.parseInt(hex,16);
      System.out.println("The value: " + value);
      System.out.println(hex + " is valid");
  }
  else{
   System.out.println("invalid");
  }

Updated:

Change your valid method as follows:

    public static boolean valid(String validString) {

        int a = 0;
        if (validString.charAt(0) == '-') {
            a = 1;
        }
        for (int i = a; i < validString.length(); i++) {
//            if (!((validString.charAt(i) >= 'A' && validString.charAt(i) <= 'F') || (validString.charAt(i) >= 0 && validString.charAt(i) <= 9))) {
//                return false;
//            }
            char ch=validString.charAt(i);
            if(!(Character.isDigit(ch) || (Character.isLetter(ch) && ((ch-'A')<=5))) ){
            return false;
           }
        }
        return true;
    }
Masudul
  • 21,823
  • 5
  • 43
  • 58
  • When I do this, the program doesn't crash anymore (so thank you!!!) but now when I enter a valid hex number, it shows up with "invalid" instead of the value. Any idea why? – user2805867 Oct 02 '13 at 06:44
  • Would you tell me which valid value you entered? – Masudul Oct 02 '13 at 06:46
  • I entered "123abc" which should work. How can I correct the result of isValid? I currently have it as a boolean set to false. – user2805867 Oct 02 '13 at 06:47
0
do {
  System.out.print("Do you want to enter a hexadecimal number? ");
  System.out.print("y or n?: ");
  choice = keyboard.next().charAt(0);
  int base = 10;
  switch(choice)
  {
    case 'y':
      System.out.print("Enter a hexadecimal number: #");
      hex = keyboard.next();
      hex = hex.toUpperCase(); //I'm not sure if this step is necessary
      try {
          Integer value = Integer.parseInt(hex, 16);
          System.out.println("Valid hex format");
          System.out.println("Hex: " + hex);
          System.out.println("Decimal: " + value);

      }
      catch (NumberFormatException e) {
          System.out.println("Invalid hex format");
          System.out.println("Input: " + hex);
      }
      break;
    case 'n':
      System.out.print("Quit");
      break
  }
} while (choice != 'n');

Now you can delete all your helper methods

Ron
  • 1,450
  • 15
  • 27
0

Your program is crashing because you are not handling the exception that is thrown when an invalid hexadecimal value is entered. The Integer.parseInt() method throws a NumberFormatException if the string it is passed cannot be parsed as a number. In your code, you are not checking for this exception, so your program will crash if an invalid hexadecimal value is entered.

To fix this, you can add a try-catch block around the call to Integer.parseInt(). The try-catch block will catch the NumberFormatException and print a message indicating that the value is invalid.

Here is the modified code:

public static void main(String[] args) throws IOException {

  Scanner keyboard = new Scanner(System.in);

  String hex;
  char choice = 'y';
  boolean isValid = false;

  do {
    System.out.print("Do you want to enter a hexadecimal number? ");
    System.out.print("y or n?: ");
    choice = keyboard.next().charAt(0);

    switch (choice) {
      case 'y':
        System.out.print("Enter a hexadecimal number: #");
        hex = keyboard.next();
        hex = hex.toUpperCase();
        int hexLength = hex.length();
        isValid = valid(hex);

        try {
          Integer value = Integer.parseInt(hex, 16);
          System.out.println("The value: " + value);

          if (isValid) {
            System.out.println(hex + " is valid");
          }
        } catch (NumberFormatException e) {
          System.out.println(hex + " is invalid");
        }

        break;
      case 'n':
        System.out.print("Quit");
    }
  } while (choice != 'n');
}

This code will first check if the value entered is valid using the valid() method. If the value is valid, the Integer.parseInt() method will be called to convert the value to a decimal number. If the value is invalid, the NumberFormatException will be caught and a message will be printed indicating that the value is invalid.

offo10
  • 1
  • Although this catches the exception, the main issue with the original posted code is that despite calling `valid(hex)` method to determine whether or not a String contains valid hex characters, the result of the valid method is ignored, and the String is parsed irrespective of whether or not it contains a valid hex string. – roj Aug 30 '23 at 05:13