-2

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!!!

TheLittleCoder
  • 21
  • 2
  • 11
  • Very little coder. In other words, "Please code this simple method for me." Someone might, but you'll get more out of it if you try something. – duffymo Dec 06 '16 at 23:33
  • I'm not sure but would this work? catch (NoSuchElementException e) { return false; } – TheLittleCoder Dec 06 '16 at 23:37
  • The JVM is your friend. You cannot become a programmer by being so timid. Run the code; see if it meets your requirements. If it doesn't, fix it until it does. Here's a hint: At no time do you compare the number of tokens you get with the value you pass in. The exception will never be thrown until you iterate over the number of tokens. There's also a countTokens method that might be of interest to you. – duffymo Dec 06 '16 at 23:56
  • Here's another hint: Learn how to use JUnit to test your methods and classes. There are a lot of possibilities in your method. You can test all of them with a good unit test class. – duffymo Dec 06 '16 at 23:59

2 Answers2

0

Here's how I might do it. Not what you had in mind, but I wanted to show you JUnit.

StringUtils.java:

package utils;

import java.util.Arrays;
import java.util.List;

/**
 * @author Michael
 * @link https://stackoverflow.com/questions/41006856/how-do-i-catch-a-nosuchelementexception?noredirect=1#comment69222264_41006856
 */
public class StringUtils {

    private StringUtils() {}

    public static List<String> tokenize(String str) {
        String [] tokens = new String[0];
        if (isNotBlankOrNull(str)) {
            str = str.trim();
            tokens = str.split("\\s+");
        }
        return Arrays.asList(tokens);
    }

    public static boolean isBlankOrNull(String s) {
        return ((s == null) || (s.trim().length() == 0));
    }

    public static boolean isNotBlankOrNull(String s) {
        return !isBlankOrNull(s);
    }

    public static boolean hasSufficientTokens(int numTokens, String str) {
        return (numTokens >= 0) && tokenize(str).size() >= numTokens;
    }
}

StringUtilsTest.java:

package utils;

import org.junit.Assert;
import org.junit.Test;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * Created by Michael
 * Creation date 12/6/2016.
 * @link https://stackoverflow.com/questions/41006856/how-do-i-catch-a-nosuchelementexception?noredirect=1#comment69222264_41006856
 */
public class StringUtilsTest {

    @Test
    public void testIsNotBlankOrNull_NullString() {
        Assert.assertFalse(StringUtils.isNotBlankOrNull(null));
    }

    @Test
    public void testIsNotBlankOrNull_EmptyString() {
        Assert.assertFalse(StringUtils.isNotBlankOrNull(""));
    }

    @Test
    public void testIsNotBlankOrNull_BlankString() {
        Assert.assertFalse(StringUtils.isNotBlankOrNull("        "));
    }

    @Test
    public void testIsNotBlankOrNull_FullString() {
        Assert.assertTrue(StringUtils.isNotBlankOrNull("I'm not null, blank, or empty"));
    }

    @Test
    public void testTokenize_NullString() {
        // setup
        List<String> expected = Collections.EMPTY_LIST;
        // exercise
        List<String> actual = StringUtils.tokenize(null);
        // assert
        Assert.assertEquals(expected, actual);
    }

    @Test
    public void testTokenize_EmptyString() {
        // setup
        List<String> expected = Collections.EMPTY_LIST;
        // exercise
        List<String> actual = StringUtils.tokenize("");
        // assert
        Assert.assertEquals(expected, actual);
    }

    @Test
    public void testTokenize_BlankString() {
        // setup
        List<String> expected = Collections.EMPTY_LIST;
        // exercise
        List<String> actual = StringUtils.tokenize("        ");
        // assert
        Assert.assertEquals(expected, actual);
    }

    @Test
    public void testTokenize_FullString() {
        // setup
        List<String> expected = Arrays.asList("I'm", "not", "null,", "blank,", "or", "empty");
        // exercise
        List<String> actual = StringUtils.tokenize("    I'm not     null,    blank, or empty    ");
        // assert
        Assert.assertEquals(expected.size(), actual.size());
        Assert.assertEquals(expected, actual);
    }

    @Test
    public void hasSufficientTokens_NegativeTokens() {
        // setup
        int numTokens = -1;
        String str = "    I'm not     null,    blank, or empty    ";
        // exercise
        // assert
        Assert.assertFalse(StringUtils.hasSufficientTokens(numTokens, str));
    }

    @Test
    public void hasSufficientTokens_InsufficientTokens() {
        // setup
        String str = "    I'm not     null,    blank, or empty    ";
        int numTokens = StringUtils.tokenize(str).size() + 1;
        // exercise
        // assert
        Assert.assertFalse(StringUtils.hasSufficientTokens(numTokens, str));
    }

    @Test
    public void hasSufficientTokens_NullString() {
        // setup
        String str = "";
        int numTokens = StringUtils.tokenize(str).size();
        // exercise
        // assert
        Assert.assertTrue(StringUtils.hasSufficientTokens(numTokens, str));
    }

    @Test
    public void hasSufficientTokens_Success() {
        // setup
        String str = "    I'm not     null,    blank, or empty    ";
        int numTokens = StringUtils.tokenize(str).size();
        // exercise
        // assert
        Assert.assertTrue(StringUtils.hasSufficientTokens(numTokens, str));
    }
}

It's not a good idea to use exceptions for program logic.

StringTokenizer is a JDK 1.0 vintage class. It's stood the test of time, but I would not recommend going all the way back to 1995.

duffymo
  • 305,152
  • 44
  • 369
  • 561
0

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!

TheLittleCoder
  • 21
  • 2
  • 11