Reputation:
double runde(double x, int n) {
if (n < 0) {
throw new IllegalArgumentException("Anzahl der Nachkommastellen darf nicht negativ sein.");
return 0.0 ; }
if (n==x) {/* Ist n=x? Wenn ja, dann nicht runden*/
return x ; } /* X dementsprechend als Rückgabewert */
if (n>0) {/* Test ob n größer null ist*/
return Math.round(x*Math.pow(10,n))/Math.pow(10,n) ; }}
Hey, I don't get why return 0.0 should be a unreachable statement. I tried to build a method which rounds a number to a given decimal place.
besides there shall be a missing return statement.
Thank you for your help!
Upvotes: 0
Views: 127
Reputation: 13
When you throw an exception the java compiler stops executing the current method and the control moves out of the current method, I would recommend you to use an if else statement for your problem so that if the first condition is true it does not skip over the command "return 0.0"
Upvotes: 0
Reputation: 433
By throwing an exception, you're preventing the method to execute any further.
If the exception is not catched, the entire thread will be interrupted and closed.
If you don't want that, return some value that can only mean an error
Upvotes: 0
Reputation: 394146
If your method throws an exception, it can't return a value too.
You must choose whether to throw an exception:
if (n < 0) {
throw new IllegalArgumentException("Anzahl der Nachkommastellen darf nicht negativ sein.");
}
or to return 0.0
:
if (n < 0) {
return 0.0 ;
}
but you can't do both.
And you must have a final return statement in case none of your conditions are true. Add a return statement as the final statement of the method.
Upvotes: 3
Reputation: 122026
You are not missing a return statement. Actually you have that extra. Once you throw exception, the executions terminates there. Hence there is no chance of reaching that return. Hence the return line is unreachable. Depending on your business choose a one. Either return or an exception.
Upvotes: 1
Reputation: 382464
You throw an exception the statement just before.
This ends the execution of the method.
It's possible you're confused by the random indentation and braces placement. You should try to stick to a standard formatting. Writing clean code helps avoiding bugs.
Upvotes: 0