Converting Hexadecimal String to Decimal Integer

后端 未结 14 1989
感动是毒
感动是毒 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:46

    //package com.javatutorialhq.tutorial;
    
    import java.util.Scanner;
    
    /* * Java code convert hexadecimal to decimal */ 
    public class HexToDecimal {
    
        public static void main(String[] args) {
    
            // TODO Auto-generated method stub 
    
            System.out.print("Hexadecimal Input:");
    
            // read the hexadecimal input from the console 
    
            Scanner s = new Scanner(System.in); 
    
            String inputHex = s.nextLine();
    
            try{ 
    
    // actual conversion of hex to decimal
    
                Integer outputDecimal = Integer.parseInt(inputHex, 16);
    
                System.out.println("Decimal Equivalent : "+outputDecimal);
    
    
            }
    
            catch(NumberFormatException ne){
    
                // Printing a warning message if the input is not a valid hex number
    
                System.out.println("Invalid Input"); 
    
            }
    
            finally{ s.close();
    
            }
        } 
    }
    

提交回复
热议问题