简体   繁体   English

扫描仪中的next()方法不等待输入

[英]the next() method in the Scanner doen't wait for input

i wrote this line (String str = sc.next();) like 10 times in my code, and all of them work ok except for one that doesn't wait for my input and immediately throws an exception "java.util.NoSuchElementException" ! 我在我的代码中写了这行代码(String str = sc.next();)就像10次一样,除了不等待我的输入并立即引发异常“ java.util.NoSuchElementException”之外,其他所有代码都可以正常工作!! does any one have an idea why that could happen ?? 没有人知道为什么会发生吗?

private static Matrix GetRationalMatrix(int[] size) throws Exception {
    Scanner sc = new Scanner(System.in);
    MathVector[] matrix = new MathVector[size[0]];
    for(int i = 0 ; i < size[0] ; i++) {
        MathVector vector = null;
        String str = sc.nextLine();
        str = str.replaceAll("[ \t]+", " ");
        String[] splitStr = str.split(" ");
        Scalar[] scalarVector = new Scalar[size[1]];
        for(int j = 0 ; j < splitStr.length ; j++) {
            String[] tmp = splitStr[j].split("/");
            try {
                scalarVector[j] = new Rational(Integer.parseInt(tmp[0]), Integer.parseInt(tmp[1]));
            }
            catch(Exception e){
                sc.close();
                throw new Exception("Please enter values properly: a/b were a,b are integers!");
            }
        }
        vector = new MathVector(size[1], scalarVector);
        matrix[i] = new MathVector(vector);
    }
    Matrix ans = new Matrix(size[0], matrix);
    sc.close();
    return ans;
}

in size[0] the number of rows and in size[1] number of columns , both will be positive integers 在size [0]的行数和在size [1]的列数中,两者均为正整数

nextLine( ) instead of next(); nextLine( )代替next();

Both hasNext and next methods may block waiting for further input. hasNext和next方法都可能会阻塞等待进一步的输入。 Whether a hasNext method blocks has no connection to whether or not its associated next method will block. hasNext方法是否阻塞与其关联的next方法是否将阻塞无关。

If you previously used 如果您以前使用过

Scanner sc = new Scanner(System.in);

inside a try-with-resources or closed the Scanner yourself, that would have closed the underlying System.in stream. 在try-with-resources中或自己关闭Scanner ,这将关闭基础System.in流。 In that case, trying to read from it again through a Scanner would cause a NoSuchElementException . 在这种情况下,尝试通过Scanner再次读取它会导致NoSuchElementException

Don't close System.in and try to re-use the same Scanner object. 不要关闭System.in并尝试重新使用同一Scanner对象。

The javadoc for hasNext() specifies: hasNext()的javadoc指定:

Returns true if this scanner has another token in its input. 如果此扫描程序的输入中包含另一个令牌,则返回true。 This method may block while waiting for input to scan. 等待输入扫描时,此方法可能会阻塞。 The scanner does not advance past any input. 扫描仪不会前进超过任何输入。

The javadoc for next() specifies: next()的javadoc指定:

Finds and returns the next complete token from this scanner. 查找并返回此扫描仪的下一个完整令牌。 A complete token is preceded and followed by input that matches the delimiter pattern. 完整的标记在其前面,然后是与定界符模式匹配的输入。 This method may block while waiting for input to scan, even if a previous invocation of hasNext() returned true. 即使先前调用hasNext()返回true,此方法也可能在等待输入扫描时阻塞。

That does not mean next() will always block, but it might block, say if it's waiting for the end of the token, since it promises to return the next complete token from the input. 并不意味着next()总是会阻止,但它可能会阻止,说如果它等待令牌的结束 ,因为它有望从输入返回下一个完整标记。 Checking whether the input contains another token is an entirely different operation, performed by hasNext() , which will block because it will wait for input (until EOF is found). 检查输入是否包含另一个令牌是完全不同的操作,由hasNext()执行,该操作将阻塞,因为它将等待输入(直到找到EOF为止)。

So I think you're getting NoSuchElementException because you are using next() improperly. 所以我认为您正在获取NoSuchElementException因为您使用了不正确的next()

java.util.NoSuchElementException is a RuntimeException which can be thrown by different classes in Java like Iterator, Enumerator, Scanner or StringTokenizer. java.util.NoSuchElementException是一个RuntimeException,可以由Java中的不同类(如Iterator,Enumerator,Scanner或StringTokenizer)引发。 All of those classes has method to fetch next element or next tokens if underlying data-structure doesn't have any element Java throws "java.util.NoSuchElementException". 如果基础数据结构没有任何元素,则所有这些类都具有获取下一个元素或下一个标记的方法,Java抛出“ java.util.NoSuchElementException”。

u can use a string tokenizer in our code.. 您可以在我们的代码中使用字符串标记器。

StringTokenizer st=new StringTokenizer(sc); StringTokenizer st =新的StringTokenizer(sc);

u can use hasMoretokens() method....so that it returns true as long as the input u provided have more tokens..... 您可以使用hasMoretokens()方法....以便只要您提供的输入具有更多令牌,它就返回true .....
incase u want to get next token u can nextToken() method... 万一您想获取下一个令牌,可以使用nextToken()方法...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM