0

The problem is this: Write the code that will translate hexadecimal digits (A - F, accept lower and uppercase) to its decimal values.

The input contains an character. If it is the hexadecimal digit print its decimal value else print -1.

I have a solution but I don't properly understand this line ch = input.nextLine().charAt( 0 );

import java.util.Scanner;

public class JavaApp {

    public static void main(String[] args) {

      Scanner input = new Scanner(System.in);
      char ch;
      int digit;
  
      ch = input.nextLine().charAt( 0 );
      if( ch >= '0' && ch <= '9') digit = ch - '0';
      else 
          if( ch >= 'a' && ch <= 'f') digit = ch - 'a' +10;
          else  
              if( ch >= 'A' && ch <= 'F') digit = ch - 'A' +10;
              else digit = -1;
      
      System.out.println( digit );
    }
}

Thanks for help

Umutambyi Gad
  • 4,082
  • 3
  • 18
  • 39
  • 2
    `input.nextLine().charAt( 0 );` gets your the first character read from the line returned by the `Scanner` object (which uses `System.in` as the source of data). – Progman Oct 18 '20 at 12:29

2 Answers2

0

Because the input you get from the Scanner is a String it gets converted to a char by charAt.

Emjay1639
  • 51
  • 1
0

Scanner does not support nextChar() to read a single character. https://www.geeksforgeeks.org/gfact-51-java-scanner-nextchar/

Hence, even though the input given in STDIN is a single character, Scanner.nextLine() considers it as String. So, in order to get first character of that String, charAt(0) is being used.

More info on scanner nextLine() method - https://www.baeldung.com/java-scanner-nextline

Updated:

To make sure the character is digit, Character.isDigit can be used. What is the best way to tell if a character is a letter or number in Java without using regexes?

tanmayghosh2507
  • 773
  • 3
  • 12
  • 31