Converting Hexadecimal String to Decimal Integer

后端 未结 14 1984
感动是毒
感动是毒 2020-12-09 16:02

I wrote some code to convert my hexadecimal display string to decimal integer. However, when input is something like 100a or 625b( something with letter) I got an error like

14条回答
  •  生来不讨喜
    2020-12-09 16:48

    Well, Mr.ajb has resolved and pointed out the error in your code.

    Coming to the second part of the code, that is, converting a string with letters to decimal integer below is code for that,

    import java.util.Scanner;
    
    public class HexaToDecimal
    {
       int number;
    
       void getValue()
       {
          Scanner sc = new Scanner(System.in);
          System.out.println("Please enter hexadecimal to convert: ");
          number = Integer.parseInt(sc.nextLine(), 16);
          sc.close();
       }
    
       void toConvert()
       {
          String decimal = Integer.toString(number);
          System.out.println("The Decimal value is : " + decimal);
       }
    
       public static void main(String[] args)
       {
          HexaToDecimal htd = new HexaToDecimal();
          htd.getValue();
          htd.toConvert();
       }
    }
    

    You can refer example on hexadecimal to decimal for more information.

提交回复
热议问题