如何将随机数转换为字符

问题描述 投票:0回答:4

我已尝试将随机数转换为字符。如果我在变量中键入数字,则可以使用,但是如果执行此操作int number = (int)(Math.random()*10);,然后将其分配给char并在打印时将其转换为char c = (char)number;,则它不会显示任何内容,没有错误,如看不见的字符。您能帮我做到这一点吗?

java random ascii
4个回答
1
投票

只需将'0'添加到int

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

由于'0'是ASCII值48,'1'是49,依此类推...,如果您将其相加,则从0到9的任何数字都会导致其ASCII值介于'0''9'之间的数字。


0
投票

您使用的是0到9之间的随机数。当尝试将其转换为整数时,可以从ASCII表中获得此可能的值

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) 

所以您需要检查ASCII table以使用Char


0
投票

使用整数并转换为字符串。

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

0
投票

之所以发生这种情况,是因为您得到一个从09的数字,该数字对应于不可打印的字符。尝试以下代码:

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);
    }
}

将打印ASCII范围为33至126的字符。

© www.soinside.com 2019 - 2024. All rights reserved.