I\'m very new to Java. Eclipse is giving me the error
The method must return a result of type int
for the following code:
Only one public top level class (a top level class is a class not contained in another class) is allowed per .java file.
Define funk
in funk.java with no other top level classes.
Put any other top level classes in their own files where the file name matches the class name.
Regarding your second question, if you declare a method to return a particular type, like int
, then all paths through that method must result in a return
statement returning a valid value. In your example, the if
statement might not be entered!
What happens if b == a
or a < b
?
public class firstprog {
public static int largest(int a,int b,int c)
{
if(a>b)
{
if(a>c)
{
return a;
}
else if(b>c)
{
return b;
}
else
{
return c;
}
}
return 0;
}
public static void main(String args[]) {
int a=7;
int b=8;
int c=9;
System.out.println(largest(a,b,c));
}
}
Note: you have to add return statement, because a is not greater then b, so it it not going inside of if block.. In your larget(...) it is expecting return statement as int.. so you have to add one more return statement. then it work ... Cheers ...!!!
Are you trying to put multiple classes into one file? Each class should get its own .java file with the appropriate name. Also make the first letter of your class upper case, as this is the naming convention.
As an aside, your function will only work if a is larger than c. You've missed out on some cases.
EDIT: you can have nested classes, but I think you might want to stay away from stuff like that for now.
Why is this so?
If you mean "why do I get this error", it's because you have not put the class in its own file, and you must. If you mean "why must I put the class in its own file", it's because Java says so: one public
type (class or interface) per file.
Specifically, "its own" file must have the same name: the public class funk
goes in funk.java
, and the public class firstprog
goes in firstprog.java
.
Yes the problem is that you can only have one public class per file and this file should have the same name than the class. You can just remove the public in front of the definition of the first class. A better way to do would be to make it a static method of the main class.
To solve you second problem you can do this:
public class firstprog {
public static int largest(int a,int b,int c)
{
if(a>b)
{
if(a>c)
return a;
else
if(b>c)
return b;
else
return c;
}
else
{
if(b>c)
return b;
else
return c;
}
}
public static void main(String args[]) {
int a=19;
int b=2;
int c=1;
System.out.println(largest(a,b,c));
}
}
In Java public classes must be in separate files with name the same as class name.
So put your funk class in funk.java file and firstprog class in firstprog.java file
Or delete public
in funk class, then this class will have default package modifier.