NoElementException 但我打印元素并得到预期结果

发布于 2024-07-13 16:17:07 字数 1321 浏览 6 评论 0原文

我想做的是将 Move 对象保存到名为 topMoves 的 Vector 中。 将会有许多 Move 对象,这就是我在循环内创建对象的原因。

PastPriceMap 存储过去某个时间(在本例中为一分钟前)的股票价格。 currPriceMap 存储最后一秒内某个时间的股票价格。

我收到以下异常:

Exception in thread "Timer-0" java.util.NoSuchElementException

这是导致问题的行: amove.setInitPrice(pastPriceMap.get(iter.next()));

代码片段如下。 当我执行 System.out.println 语句时,我得到了预期的输出:

Iterator<String> iter = sortedTopCodes.iterator();

while(iter.hasNext()){

    System.out.println(currPriceMap.get(iter.next()));
    System.out.println(pastPriceMap.get(iter.next()));

        Move amove = new Move();
    amove.setSecCode(iter.next());
    amove.setPrice(currPriceMap.get(iter.next()));
    amove.setInitPrice(pastPriceMap.get(iter.next()));
    topMoves.add(amove);
}

    return topMoves;

Move 类如下所示:

private String secCode;
private double price;
private double initPrice;

public String getSecCode() {
    return secCode;
}
public void setSecCode(String secCode) {
    this.secCode = secCode;
}
public double getPrice() {
    return price;
}
public void setPrice(double price) {
    this.price = price;
}

public double getInitPrice() {
    return initPrice;
}
public void setInitPrice(double lastPrice) {
    this.initPrice = lastPrice;
}

What I am trying to do is save a Move objects into a Vector called topMoves. There will be many Move objects which is why I create the object within the loop.

The pastPriceMap stores prices for stocks at some past time (in this case one minute ago). The currPriceMap stores price for stocks some time within the last second.

I get the following exception:

Exception in thread "Timer-0" java.util.NoSuchElementException

This is the line that is causing the problem:
amove.setInitPrice(pastPriceMap.get(iter.next()));

The code snippet is below. When I do the System.out.println statements I get the expected output:

Iterator<String> iter = sortedTopCodes.iterator();

while(iter.hasNext()){

    System.out.println(currPriceMap.get(iter.next()));
    System.out.println(pastPriceMap.get(iter.next()));

        Move amove = new Move();
    amove.setSecCode(iter.next());
    amove.setPrice(currPriceMap.get(iter.next()));
    amove.setInitPrice(pastPriceMap.get(iter.next()));
    topMoves.add(amove);
}

    return topMoves;

The Move class looks like this:

private String secCode;
private double price;
private double initPrice;

public String getSecCode() {
    return secCode;
}
public void setSecCode(String secCode) {
    this.secCode = secCode;
}
public double getPrice() {
    return price;
}
public void setPrice(double price) {
    this.price = price;
}

public double getInitPrice() {
    return initPrice;
}
public void setInitPrice(double lastPrice) {
    this.initPrice = lastPrice;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

最佳男配角 2024-07-20 16:17:10
// while there are more lines
while(scanner.hasNextLine())
{
    final String   line;
    final String[] words;

    // get the next line
    line = scanner.nextLine();

    // break the line up into the words (\\s+ should break it up via whitespace)
    words = line.split("\\s");

    if(words.length != 5)
    {
        throw new WhateverExceptionMakesSense(line + " must contain 5 words");
    }

    System.out.println(currPriceMap.get(words[0]));
    System.out.println(pastPriceMap.get(words[1]));

    Move amove = new Move();
    amove.setSecCode(words[2]);
    amove.setPrice(currPriceMap.get(words[3]));
    amove.setInitPrice(pastPriceMap.get(words[4]));
    topMoves.add(amove);
}
// while there are more lines
while(scanner.hasNextLine())
{
    final String   line;
    final String[] words;

    // get the next line
    line = scanner.nextLine();

    // break the line up into the words (\\s+ should break it up via whitespace)
    words = line.split("\\s");

    if(words.length != 5)
    {
        throw new WhateverExceptionMakesSense(line + " must contain 5 words");
    }

    System.out.println(currPriceMap.get(words[0]));
    System.out.println(pastPriceMap.get(words[1]));

    Move amove = new Move();
    amove.setSecCode(words[2]);
    amove.setPrice(currPriceMap.get(words[3]));
    amove.setInitPrice(pastPriceMap.get(words[4]));
    topMoves.add(amove);
}
扎心 2024-07-20 16:17:09

简短回答:

对于每次调用 hasNext() ,应该只调用一次 next()

在您的代码中,您有 5 个 next()只有一个 hasNext()

在这里,阅读以下内容: http://java.sun.com/javase/6/docs/api/java/util/Iterator.html

编辑

更长的答案:

基本上迭代器是用于......很好地迭代“某物”的元素,通常是一个集合,但它可以是任何东西(假设任何东西返回一个 Iterator )。

由于您可能不知道该“任何东西”有多少个元素,因此必须有一种方法来停止迭代,对吗? (如果它是一个数组,您可以通过 length 属性来判断,但迭代器用于“封装”实现中使用的数据结构)无论如何。

迭代器 API 定义了这两个方法

-hasNext(): boolean 
-next(): Object ( or <E> since Java 1.5 ) 

因此典型的习惯用法是这样的:

 while( iterator.hasNext() ) { // reads: while the iterator has next element
      Object o = iterator.next(); //  give me that element
 }

如果迭代器只有两个项目会发生什么?

 while( iterator.hasNext() ) { // the first time will return true, so the next line will be executed.

      Object o = iterator.next(); // give me that item. ( 1st element ) 

      Object b = iterator.next(); // oops dangerous by may work ... ( 2nd element ) 

      Object c = iterator.next(); // eeeerhhh... disaster: NoSuchElementException is thrown.

}

这就是发生在你身上的事情。 您没有验证迭代器是否有另一个元素,您只是检索它。 如果迭代器碰巧有一些元素,它可能会工作一段时间,但有一段时间(正如您刚刚看到的)它会失败。

顺便说一句,不要考虑捕获 NoSuchElementException。 这是一个运行时异常,它表明代码逻辑中的某些内容应该修复。

请参阅此答案了解有关异常的更多信息。

Short answer:

For each call to hasNext() there should be only one call to next()

In your code you have 5 next() with only one hasNext()

Here, read this: http://java.sun.com/javase/6/docs/api/java/util/Iterator.html

EDIT

Longer answer:

Basically an iterator is used to ... well iterate the elements of "something" tipically a collection but it could be anything ( granted that anything returns an Iterator ).

Since you may not know how many elements does that "anything" have, there must be a way to stop iterating right? ( if it was an array, you can tell by the length property, but the iterator is used to "encapsulate" the data structure used in the implementation ) Anyway.

The iterator API defines these two methods

-hasNext(): boolean 
-next(): Object ( or <E> since Java 1.5 ) 

So the typical idiom is this:

 while( iterator.hasNext() ) { // reads: while the iterator has next element
      Object o = iterator.next(); //  give me that element
 }

What happens if the iterator has only two items?

 while( iterator.hasNext() ) { // the first time will return true, so the next line will be executed.

      Object o = iterator.next(); // give me that item. ( 1st element ) 

      Object b = iterator.next(); // oops dangerous by may work ... ( 2nd element ) 

      Object c = iterator.next(); // eeeerhhh... disaster: NoSuchElementException is thrown.

}

This is what is happening to you. You did not verify if the iterator has another element, you just retrieve it. If the iterator happens to have some elements, it may work for a while but there will be a time ( as you just saw ) when it fails.

By the way, DO NOT even think in catching NoSuchElementException. That's a runtime exception and it indicates that something in your code logic should be fixed.

See this answer to know more about the exceptions.

九局 2024-07-20 16:17:09

这是使用新 for 循环的版本:

for ( String secCode : secCodeList ) {

        System.out.println(currPriceMap.get(secCode));
        System.out.println(pastPriceMap.get(secCode));

        Move amove = new Move();
        amove.setSecCode(secCode);
        amove.setPrice(currPriceMap.get(secCode));
        amove.setInitPrice(pastPriceMap.get(secCode));
        topMoves.add(amove);
}

以旧方式:

String secCode = null;    
for ( Iterator<String> it = secCodeList.iterator(); it.hasNext() ) {
    secCode = it.next();
    System.out.println(currPriceMap.get(secCode));
    System.out.println(pastPriceMap.get(secCode));

    Move amove = new Move();
    amove.setSecCode(secCode);
    amove.setPrice(currPriceMap.get(secCode));
    amove.setInitPrice(pastPriceMap.get(secCode));
    topMoves.add(amove);
 }

Here is a version using the new for loops:

for ( String secCode : secCodeList ) {

        System.out.println(currPriceMap.get(secCode));
        System.out.println(pastPriceMap.get(secCode));

        Move amove = new Move();
        amove.setSecCode(secCode);
        amove.setPrice(currPriceMap.get(secCode));
        amove.setInitPrice(pastPriceMap.get(secCode));
        topMoves.add(amove);
}

in the older fashion :

String secCode = null;    
for ( Iterator<String> it = secCodeList.iterator(); it.hasNext() ) {
    secCode = it.next();
    System.out.println(currPriceMap.get(secCode));
    System.out.println(pastPriceMap.get(secCode));

    Move amove = new Move();
    amove.setSecCode(secCode);
    amove.setPrice(currPriceMap.get(secCode));
    amove.setInitPrice(pastPriceMap.get(secCode));
    topMoves.add(amove);
 }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文