nus-cs2030 / 2021-s1

27 stars 48 forks source link

Lab 7 NoSuchElementException #559

Closed toastanddrink closed 3 years ago

toastanddrink commented 3 years ago

Hi, does anyone know how to throw a NoSuchElementException for this? Previously the exception was thrown but as I proceeded higher on to the other levels the exception is not thrown anymore and I wonder why?

Thank you in advance!

Screenshot 2020-11-29 at 9 28 04 PM Screenshot 2020-11-29 at 9 28 10 PM
xie-ran commented 3 years ago

Hi! I guess u can change ur Optional.ofNullable() to Optional.of(), and you should use Optional.of() in ur Lazy.of() method as well. Hope this helps!

CWei88 commented 3 years ago

For NoSuchElementException, you should make use of orElseThrow() in the Optional class. This should be put in your of() method and not your get() method.

itmeruoxin commented 3 years ago

Optional has a method orElseThrow() that returns the value if present and throws NoSuchElementException if empty

toastanddrink commented 3 years ago

Hi, currently my of() is just

static <T extends Comparable<T>> Lazy<T> of(T v) {
        return new Lazy<T>(()->v); 
    }

    static <T extends Comparable<T>> Lazy<T> of(Supplier<T> s) {
        return new Lazy<T>(s); 
    }

and im not v sure how to go about changing it without affecting the rest?

xie-ran commented 3 years ago

Hi, you can change your of() by trying to creating an Optional.of(v), and catch the exception thrown by this method. So basically inserting these lines of code before the return statement.

  try {
      Optional<T> t = Optional.of(v);
  } catch (Exception e) {
      throw new NoSuchElementException("No value present");
  }
egsclgns commented 3 years ago

For your of() that takes in the Supplier, you can use Optional.ofNullable to wrap your s in an Optional, and then use orElseThrow() on it when you put it in the Lazy constructor.

pikasean commented 3 years ago

For the NoSuchElementException, you can change s to Optional.ofNullable(s).orElseThrow(). For the NullPointerException, you can change return v to return value.orElseThrow(() -> new NullPointerException()).

toastanddrink commented 3 years ago

thank u all of you guys for the help!