Reputation:
i'm learning how to return a value and try to write the following code;
public class JustTryingReturn {
static int a, b;
static Scanner sc = new Scanner(System.in);
static int nganu() {
return a+b;
}
public static void main(String[] args) {
int c = nganu();
System.out.println("Enter number ");
a = sc.nextInt();
b = sc.nextInt();
System.out.println(c);
}
}
But the output always print 0 instead of a+b
. What did i do wrong?
Thank you.
Upvotes: 0
Views: 59
Reputation: 8387
Try to use this just change of order of this line:
int c = nganu();
a = sc.nextInt();
b = sc.nextInt();
LIke this:
public class JustTryingReturn {
static int a, b;
static Scanner sc = new Scanner(System.in);
static int nganu() {
return a+b;
}
public static void main(String[] args) {
// the order was changed
System.out.println("Enter number ");
a = sc.nextInt();
b = sc.nextInt();
int c = nganu();
System.out.println(c);
}
}
Upvotes: 1
Reputation: 4207
Please change your code accordingly,
public static void main(String[] args) {
//int c = nganu(); // here first time a,b is 0, still you haven't assign...
System.out.println("Enter number ");
a = sc.nextInt(); // now, actually you have assign value to a
b = sc.nextInt(); // now, actually you have assign value to b
int c = nganu();
System.out.println(c);
}
Upvotes: 0
Reputation: 15310
You have to call your function after you assign values to a
and b
.
So put this: int c = nganu();
after you get a
and b
.
Upvotes: 1
Reputation: 393801
You should make the call
int c = nganu();
after you assign the input values of a
and b
. Otherwise they'll still contain 0
by default when you compute their sum.
System.out.println("Enter number ");
a = sc.nextInt();
b = sc.nextInt();
int c = nganu();
System.out.println(c);
Upvotes: 1