Home » Java » java – How do I convert a random number in to a character-Exceptionshub

java – How do I convert a random number in to a character-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have tried to convert a random number into a character.
If I type a number into a variable it works, but if I do this int number = (int)(Math.random()*10); and then to assign it to a char and convert it char c = (char)number; when I print it, it shows nothing without errors like an invisible character.
Could you help me to do this?

How to&Answers:

Just add '0' to your int.

int number = (int)(Math.random()*10);
char c = (char)number + '0';

Since '0' is ASCII value 48, '1' is 49, etc…, any number from 0 to 9 you sum to it will result in a number whose ASCII value is between between '0' and '9'.

Answer:

You are using a random from 0 to 9. And when trying to convert that to an integer you can have this possible values from the ASCII table

Dec  Char                         
---------                         
  0  NUL (null)                   
  1  SOH (start of heading)       
  2  STX (start of text)          
  3  ETX (end of text)            
  4  EOT (end of transmission)    
  5  ENQ (enquiry)                
  6  ACK (acknowledge)            
  7  BEL (bell)                   
  8  BS  (backspace)              
  9  TAB (horizontal tab)         
 10  LF  (NL line feed, new line) 

So you need to check the ASCII table for the Char to use

Answer:

Use an Integer and convert to String.

public class Main {
    public static void main(String[] args) {
        Integer number = new Integer(Math.random() * 10);
        String c = number.toString();
        System.out.println(c);
    }
}

Answer:

It is happening because you are getting a number from 0 to 9 which corresponds to a non-printable character. Try the following code:

import java.util.Random;

public class Main {
    public static void main(String[] args) {
        int number = new Random().nextInt((126 - 33) + 1) + 33;
        char c = (char) number;
        System.out.println(c);
    }
}

This will print some character from the ASCII range of 33 to 126.