English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

thanks for any help!

class CompareNumbers {

public static void main(String[] args) {

System.out.println(compare(1,2,3));

}

static String compare(int num, int num2, int num3) {

if(num < num2)
if(num2 < num3) return num+" is less than "+num2+", "+num2+" is less than "+num3;
else return "the numbers are not in ascending order";

}

}

2007-08-04 02:56:32 · 3 answers · asked by Anonymous in Computers & Internet Programming & Design

3 answers

There is a compile error because compare() doesn't always return a String as you have written it. Let's add braces to explicitly identify what happens (and some dots to indent it):

if (num < num2) {
. . . if (num2 < num3) {
. . . . . . return num+" is [...];
. . . } else {
. . . . . . return "the numbers [...]";
. . . }
}

What happens if num>=num2? The first if statement evaluates to "false" and everything inside those braces -- including the second if-else -- is not executed. This means there is no return value, the execution hits the bottom of the method without returning any value. When you declare a method that returns String, EVERY possible path through the method MUST return a String (or return null, or throw an exception).

The compiler "knows" if there is a path to the bottom of the method that implies no return value, and will complain if a method has a declared return type (i.e., anything other than "void") AND such a path exists.

What you want, I think, is this:

if ((num < num2) && (num2 < num3))
return num + " is [...];
else return "the numbers are not [...]";

In this case, both branches of the if statement return a String, and there is no path to the bottom of the method without returning anything.

2007-08-04 05:35:01 · answer #1 · answered by McFate 7 · 1 0

What is the error you are getting?

2007-08-04 11:05:11 · answer #2 · answered by jonathanlks 4 · 0 0

http://java3.blogspot.com/

Tutorials- http://teamtutorial.com/

software engineering tools- http://tigri.org/

Java tutorials- http://java-tip.org/

2007-08-04 12:29:32 · answer #3 · answered by aerokan a 3 · 0 2

fedest.com, questions and answers