javatypecast-operator

How to use cast operator


I'm currently working on a problem in my homework. The question is:

"Write a program that prompts the user to input an integer between 0 and 35. If the number is less than or equal to 9, the program should output the number; otherwise, it should output A for 10, B for 11, C for 12, ..., and Z for 35. (Hint: Use the cast operator, static_cast() for numbers >= 10."

I don't know how to use the cast operator and I need some guidance.

Here is my code:

import java.util.Scanner;
public class Question_4 {
public static void main(String args[]){
    Scanner sc = new Scanner(System.in);
    int integer = 0;

    System.out.println("Enter a number between 0 - 35: ");
    integer = sc.nextInt();

    if(integer <= 9){
        System.out.println("Number entered is " + integer);
    }
    else{

        System.out.println(static_cast.class<char>('A' + (integer - 
                                                            10)););
    }
}//END Main
}

Solution

  • you can do it like this:

    System.out.println((char)((byte)'A' + (integer - 10)) );