如何捕获NoSuchElementException? [英] How do I catch a NoSuchElementException?

查看:176
本文介绍了如何捕获NoSuchElementException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个函数,它返回一个布尔类型,它是否有足够的标记。我使用下面的代码来做这件事:

I am making a function that returns a Boolean type of whether a String has enough tokens. I do this by using this code:

public boolean isEnoughTokens(int tokens, String problem) {
        try {
            StringTokenizer token = new StringTokenizer(problem);
            return true;
        } catch (NoSuchElementException ) {

        }
    }

问题是,我还没有想出如何捕获一个没有这样的元素异常。我认为它非常简单,但仍然没有弄清楚如何去做。

The problem is that I haven't figured out how to catch a No such element exception. I think it's super simple but still didn't figure out how to do it.

谢谢,任何帮助我们都会很感谢!!!

Thanks, any help will be appreciated!!!

推荐答案

我想我找到了自己问题的答案!

I think I found the answer to my own question! I was messing around and thanks to you informing me about the countTokens() function I came up with this!

public boolean isEnoughTokens(int tokens, String problem) {
        try {
            StringTokenizer token = new StringTokenizer(problem);
            if (token.countTokens() == tokens) {
                return true;
            }
            else {
                return false;
            }
        } catch (NoSuchElementException e) {
            return false;
        }
    }

我不知道是否有任何错误,但到目前为止,当我测试它,它的工作!

I don't know if there is any error but so far when I tested it, it works!

这篇关于如何捕获NoSuchElementException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆