我刚开始学习Java,我正在尝试做一个猜数字游戏,无论如何我正在使用
int guess = Integer.parseInt(stringGuess);
和
inputLine = is.readLine();
Integer.parseInt(inputLine);
我想知道是否无论如何我可以让程序识别并使用一堆空格作为整数,基本上我该如何编码它以便“0”将被识别为0?
我刚开始学习Java,我正在尝试做一个猜数字游戏,无论如何我正在使用
int guess = Integer.parseInt(stringGuess);
和
inputLine = is.readLine();
Integer.parseInt(inputLine);
我想知道是否无论如何我可以让程序识别并使用一堆空格作为整数,基本上我该如何编码它以便“0”将被识别为0?
int guess = Integer.parseInt(stringGuess.trim());
请参阅http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#trim%28%29
一个更“强大”的工具是从字符串中删除所有非数字字符,可以这样完成:
int guess = Integer.parseInt(stringGuess.replaceAll("\\D", ""));
if (stringGuess!=null) {
int guess = Integer.parseInt(stringGuess.trim());
}
int guess = 0
if(stringGuess != null) {
try {
guess = Integer.parseInt(stringGuess.trim());
} catch(NumberFormatException nfe) {
// inform user that the number was bad?
}
}
如果您还需要处理数字之间的空格(或任何非数字),您可以使用:
int guess = 0
if(stringGuess != null) {
try {
guess = Integer.parseInt(stringGuess.replaceAll("[^0-9]+", ""));
} catch(NumberFormatException nfe) {
// inform user that the number was bad?
}
}
Scanner sc = new Scanner(System.in);
int guess = 0
if(sc.hasNextInt())
guess = sc.nextInt();
但是,它会将像“1 2 3 4”这样的字符串检测为四个不同的整数,而不是 1234,如果这就是您的意思的话。
trim()
只能省略前导和尾随空格。
如果你不想使用replace("\\D", "")
,我想你可以自己实现一个parseInt()
方法,你可以复制代码Integer.parseInt
并在if (s.charAt(i++) != ' ')
之前添加digit = Character.digit(s.charAt(i++),radix);
并更改Character.digit(s.charAt(i++),radix)
为Character.digit(s.charAt(i),radix)