English 中文(简体)
扩展 Java. util. Scanner
原标题:Extending java.util.Scanner

假设我想给扫描器添加一种方法,称为 extPresitiveInt () ,该方法类似于 nextInt () ,但发现负整数时,则会推出自订的 InputNegativeExption

我为什么要这样做呢?当有"时, https://stackoverflow.com/ questions/3059333/validing-input-using-java- util-scanner' > > 的解决方案使用 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);

hasnNext() 方法:

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 () 的正文, 在 nextPostiveInt () () ) 中, 并做一些小改动? 您能否在任何地方找到 nextInt () 的正文?

我道歉,我没有代码 显示任何努力,我已经做了, 但我不知道从哪里开始。

最佳回答

虽然Scant Scanner 类是最终的,但您无法扩展它, 也存在另一个解决方案。 您可以使用 < a href=" http://en.wikipedia.org/wiki/DeAcional_pattern" rel = “ nofollow” > Delegation stands 模式 。

同样,由于扫描器类中所有零星方法都公诸于众,您可以很容易地复制原始方法并稍作修改。请参见扫描器类中的源代码,您唯一需要修改的是用于匹配字符串的正则表达式,以便排除负内注。

扫描仪源代码 :

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());

为了您的目的,您可以使用硬码正则表达式。 原始正则表达式很容易被调试捕获 。

肯定不是实现的最好办法- 写许多代码和许多拷贝, 但使用起来容易,也很好。

问题回答

您无法扩展 < a href=>" "http://docs.oracle.com/javase/6/docs/api/java/ util/ Scanner.html" rel="nofollow"\\\code>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());




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签