Java 有 8 种原始(非对象/非引用)类型:
boolean
char
byte
short
int
long
float
double
如果“十进制”是指“以 10 为底的有符号整数”,那么是的,Java 支持通过byte
、short
和. 您使用哪一个取决于输入范围,但根据我所见,这是最常见的。int
long
int
如果用“十进制”表示“具有绝对精度的以 10 为基数的有符号浮点数”,类似于 C# 的Decimal
类型,那么不,Java 没有。
如果Scanner.nextInt
像我一样为您抛出错误,那么以下应该可以工作:
/* Create a scanner for the system in. */
Scanner scan = new Scanner(System.in);
/*
* Create a regex that looks for numbers formatted like:
*
* A an optional '+' sign followed by 1 or more digits; OR A '-'
* followed by 1 or mored digits.
*
* If you want to make the '+' sign mandatory, remove the question mark.
*/
Pattern p = Pattern.compile("(\\+?(\\d+))|(\\-\\d+)");
/* Get the next token from the input. */
String input = scan.next();
/* Match the input against the regular expression. */
Matcher matcher = p.matcher(input);
/* Does it match the regular expression? */
if (matcher.matches()) {
/* Declare an integer. */
int i = -1;
/*
* A regular expression group is defined as follows:
*
* 0 : references the entire regular expression. n, n != 0 :
* references the specified group, identified by the nth left
* parenthesis to its matching right parenthesis. In this case there
* are 3 left parenthesis, so there are 3 more groups besides the 0
* group:
*
* 1: "(\\+?(\\d+))"; 2: "(\\d+)"; 3: "(\\-\\d+)"
*
* What this next code does is check to see if the positive integer
* matching capturing group didn't match. If it didn't, then we know
* that the input matched number 3, which refers to the negative
* sign, so we parse that group, accordingly.
*/
if (matcher.group(2) == null) {
i = Integer.parseInt(matcher.group(3));
} else {
/*
* Otherwise, the positive group matched, and so we parse the
* second group, which refers to the postive integer, less its
* '+' sign.
*/
i = Integer.parseInt(matcher.group(2));
}
System.out.println(i);
} else {
/* Error handling code here. */
}
或者,您可以这样做:
Scanner scan = new Scanner(System.in);
String input = scan.next();
if (input.charAt(0) == '+') {
input = input.substring(1);
}
int i = Integer.parseInt(input);
System.out.println(i);
基本上只要删除“+”号(如果有的话)然后解析它。如果您要进行编程,学习正则表达式非常有用,这就是我给您的原因。但是如果这是家庭作业,你担心如果你使用超出课程范围的东西会引起老师的怀疑,那么千万不要使用正则表达式的方法。