如何将随机数转换为字符
How do I convert a random number in to a character
我试过将随机数转换成字符。
如果我在变量中输入一个数字,它就可以工作,但是如果我这样做 int number = (int)(Math.random()*10);
然后将它分配给一个 char 并在我打印它时将其转换 char c = (char)number;
,它不会像 invisible 一样没有错误地显示任何内容字符.
你能帮我做这个吗?
只需将 '0'
添加到您的 int
。
int number = (int)(Math.random()*10);
char c = (char)number + '0';
由于 '0'
是 ASCII 值 48,'1'
是 49,等等...,您将 0 到 9 中的任何数字相加得到的数字的 ASCII 值介于'0'
和 '9'
.
您使用的是从 0 到 9 的随机数。当尝试将其转换为整数时,您可以从 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)
因此您需要检查 ASCII table 以使用 Char
发生这种情况是因为您得到了一个从 0
到 9
的数字,它对应于一个不可打印的字符。试试下面的代码:
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 范围内的一些字符。
使用整数并转换为字符串。
public class Main {
public static void main(String[] args) {
Integer number = new Integer(Math.random() * 10);
String c = number.toString();
System.out.println(c);
}
}
我试过将随机数转换成字符。
如果我在变量中输入一个数字,它就可以工作,但是如果我这样做 int number = (int)(Math.random()*10);
然后将它分配给一个 char 并在我打印它时将其转换 char c = (char)number;
,它不会像 invisible 一样没有错误地显示任何内容字符.
你能帮我做这个吗?
只需将 '0'
添加到您的 int
。
int number = (int)(Math.random()*10);
char c = (char)number + '0';
由于 '0'
是 ASCII 值 48,'1'
是 49,等等...,您将 0 到 9 中的任何数字相加得到的数字的 ASCII 值介于'0'
和 '9'
.
您使用的是从 0 到 9 的随机数。当尝试将其转换为整数时,您可以从 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)
因此您需要检查 ASCII table 以使用 Char
发生这种情况是因为您得到了一个从 0
到 9
的数字,它对应于一个不可打印的字符。试试下面的代码:
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 范围内的一些字符。
使用整数并转换为字符串。
public class Main {
public static void main(String[] args) {
Integer number = new Integer(Math.random() * 10);
String c = number.toString();
System.out.println(c);
}
}