假设我想向扫描器中添加一个名为nextPositiveInt()的方法,它类似于nextInt(),只是当检测到负数时,会抛出一个自定义InputNegativeException。
当有使用的解决方案 hasNextInt()时,我为什么要这样做?虽然不那么简洁,但考虑到例外的目的,它似乎更整洁、更符合逻辑。例如:
扩展扫描方法:
Scanner cli = new Scanner(System.in);
boolean inputValid = false;
do
{
System.out.println("Enter your age:");
try
{
int age = cli.nextPositiveInt();
}
catch(InputNegativeException e)
{
System.out.println("You cannot specify a negative age.");
inputValid = false;
}
catch(InputMismatchException e)
{
System.out.println("Your input must be numeric.");
inputValid = false;
}
} while(!inputValid);hasNext() 方法:
Scanner cli = new Scanner(System.in);
do
{
System.out.println("Please enter a positive number!");
while(!sc.hasNextInt())
{
System.out.println("That's not a number!");
sc.next(); // this is important!
}
int number = sc.nextInt();
} while(number <= 0);因此,假设你还没有做出回应,告诉我为什么这是个非常糟糕的主意(如果是,请这样做;我想可能有人反对在Scanner中进行验证),我对如何做到这一点感到困惑。我想我需要在nextInt()中复制nextPositiveInt()的身体,只需做一些小的改动?你能在任何地方找到nextInt()的身体吗?
我很抱歉,我没有任何代码来显示我所做的任何努力,但我不知道从哪里开始。
发布于 2012-05-23 07:17:21
尽管Scanner类是最终的,但是您不能扩展它,还有另一个解决方案。您可以使用委托模式。
另外,由于Scanner类具有所有必要的公共方法,所以您可以轻松地复制原始方法并进行一些更改。请参阅Scanner类的源代码,您应该更改的唯一东西是regexp,用于匹配字符串,以排除负ints。
扫描仪源代码:
public int nextInt() {
return nextInt(defaultRadix);
}
public int nextInt(int radix) {
// Check cached result
if ((typeCache != null) && (typeCache instanceof Integer)
&& this.radix == radix) {
int val = ((Integer)typeCache).intValue();
useTypeCache();
return val;
}
setRadix(radix);
clearCaches();
// Search for next int
try {
String s = next(integerPattern());
if (matcher.group(SIMPLE_GROUP_INDEX) == null)
s = processIntegerToken(s);
return Integer.parseInt(s, radix);
} catch (NumberFormatException nfe) {
position = matcher.start(); // don't skip bad token
throw new InputMismatchException(nfe.getMessage());
}
}你只应该改变:
String s = next(integerPattern());为了您的目的,您可以硬编码regexp。原始的regexp很容易在调试时捕捉到。
当然,在实现方面,这不是最好的解决方案--需要编写的代码很多,复制粘贴也很多,但是使用起来很容易,也很好。
发布于 2012-05-23 07:05:58
您不能扩展Scanner,因为它是final
public final class Scanner
extends Object
implements Iterator<String>我要做的是在我的一个类中有一个助手方法:
public static int ensureNonNegative(int val) {
if (val >= 0) {
return val;
} else {
throw new InputNegativeException(val);
}
}会像这样使用它:
int val = ensureNonNegative(scanner.nextInt());https://stackoverflow.com/questions/10715009
复制相似问题