java - Why I can't return nothing in a static method this way -


i wrote piece of code train litte bit , wanted understand why cannot use notation.

public static double retanglearea (double c, double d) {   double area = c * d;   if ( c < 0 || d < 0) {     system.out.println("error.");     return;   }   return area; } 

if call method in main() shout "error." , still calculate (c * d) negative number wanted print show in. well, know how rid of problem want understand why can't way , what's problem that.

three ways round this:

  1. throw exception rather writing error console. write console in catch block arguably in better position deal error.

  2. change function return type double (note capital), , return null if don't want calculate value.

  3. use java.lang.optional<t> return type.

of these, prefer , therefore recommend 1.


Comments

Popular posts from this blog

ruby - Trying to change last to "x"s to 23 -

jquery - Clone last and append item to closest class -

c - Unrecognised emulation mode: elf_i386 on MinGW32 -