I'm trying to create a java method that returns the sum of two values x and y. Currently when I run the code, the output isn't returning anything. Is there any way I can get the value to return the sum WITHOUT modifying the "getSum(x,y);" in line 6 while using the return method???
public class ZawMethods2
{
public static void main(String[] args)
{
int x = 7, y = 45;
getSum(x,y);
}
public static int getSum(int x, int y){
int sum = x+y;
return (sum);
}
}
Thank you all in advance!!! I'm still in the beginning stage of coding so I appreciate all the help.
Sorry I thought that you are not allowed to modify getSum
method. Just add System.out.println(sum);
to getSum
method.
public class ZawMethods2
{
public static void main(String[] args)
{
int x = 7, y = 45;
System.out.print(getSum(x,y));
}
public static int getSum(int x, int y){
//no need to create temprory varibale
return x+y;
}
}
Just print it inside the getSum
method, before returning:
public static int getSum(int x, int y){
int sum = x+y;
System.out.println(sum);
return sum;
}
As mentioned by @Stultuske in the comments. if you want to only print the sum, and never get it. Then just remove the return type and aswell name the method differently for clarification:
public static void printSum(int x, int y){
System.out.println(x + y);
}
You might even want to introduce a whole new method. Leaving the old getSum
all on itself. The new method then delegates and just prints the result returned:
public static void printSum(int x, int y){
System.out.println(getSum(x, y));
}
Actually, you are compiling a program without any output. You have to use something like
System.out.println(getSum(x, y));
Otherwise you wont get any output.
If you modify the main-method like:
public static void main(String[] args)
{
int x = 7, y = 45;
int sum = getSum(x,y);
System.out.println(sum);
}
you will get the output: 52.
In this case you will save the returned Integer in sum and will print a new line to your console.
If you want to add some words, you can modify the main like:
public static void main(String[] args)
{
int x = 7, y = 45;
int sum = getSum(x,y);
System.out.println("The result is" + sum);
}
Try This:
public class ZawMethods2
{
public static void main(String[] args)
{
int x = 7, y = 45;
System.out.print(getSum(x,y));
}
public static int getSum(int x, int y)
{
int sum = x+y;
return (sum);
}
}
This code will resolve your problem very easily.
You should store your result in a variable or display a result.
int c = getSum(x,y);
or
System.out.println("The result of the two numbers are " +getSum(x,y);