+ 1
Java problem with method calling in java
Guys you understand what am trying to do here ,am calling the add() method (or function I don't know what it's called) the output gave me error that I haven't added return statement ,so I added return sum; but the output gave me infinite result of the answer like this 48 48 48 48 48 It even crashed my phone I have to restart it What is going on should I add break statement or what alternative do u guys have public class Program { public static void main(String[] args) { System.out.println("answer ="); add(); } public static int add(){ int x =6; int y=8; int sum=x*y; System.out.println(sum); } }
6 Answers
+ 3
Hello Tony Jadesola
If you only want to print the value the return type of add() need to be void:
public static void add(){
}
with return type int:
public static int add(){
int a = 3;
int b = 4;
return a+b;
}
In this case your method returns an integer. In your main:
int sum = add();
+ 3
Java sees this
public static int add()
Java thinks that function returns an `int`. But you didn't issue `return` in add() function. Java was reminding you about that.
Solution:
Return <sum> from add() ...
return sum;
P.S. There's no way you're getting infinite output unless you have a loop in the code. Is that the complete code? why I don't see any loop there ...
+ 1
Ipang that's all the code I don't know why a loop came out
+ 1
Denise RoĂberg I replaced int with void and it worked well
+ 1
Ipang thanks I figured it out