我编写了一个程序,它接受一个ASCII字符输入(它实际上需要一个String然后我使用charAt(0))到JTextField然后使用g2d.drawString()显示其十六进制,二进制,整数和八进制值。我希望能够输入"整数"值(再次实际上是字符串)并显示信息。为了分离"整数"来自" char"的值输入,我希望能够按原样输入char值,并使用模式#i
输入整数。这样,我可以使用if语句检查"整数"遵循模式,否则(否则)将输入评估为ascii" char"。如何检查字符串是否遵循此模式?
示例:
字符输入:
3 //I'll evaluate this as the ascii character value of 3
int input:
3i //I'll evaluate this as the integer value of 3
注意:整数输入可以是多位数。
答案 0 :(得分:3)
查看Pattern课程。你可以用这个做你想做的事。
答案 1 :(得分:1)
这样的东西?
if (str.length() == 1) {
char ch = charAt(0);
// code here
} else if (str.endsWith("i")) {
int num = Integer.parseInt(str.substring(0, str.length() - 1));
// code here
} else {
throw new IllegalArgumentException("Bad input: " + str);
}
如果parseInt()
之前的值无效,NumberFormatException
将抛出i
。由于这是IllegalArgumentException
的子类,因此上面的代码会为任何错误文本抛出IllegalArgumentException
。