+ 5
why it returns 5 I thought it returns 6 ?
public class MyClass { public static void main(String[ ] args) { int x = 5; addOneTo(x); System.out.println(x); } static void addOneTo(int num) { num = num + 1; } }
7 Respuestas
+ 20
👉why its not working presently ?
reason 1)U didn't assigned increased value of x to x , thatswhy it remained 5
reason 2) x is not static variable its value didn't get changed with changes U made in its in value in some function
👉to make it work through method :
step 1)do ... x=addOneTo(x); //instead of addOneTo(x);
step 2)change return type of function to int & use return keyword
//see code below
👉 here is the code :
public class MyClass {
public static void main(String[ ] args) {
int x = 5;
x = addOneTo(x);
//assigning increased value of x to x
System.out.println(x);
}
static int addOneTo(int num) {
return num = num + 1;
}
}
👉U can try making x as static variable , then u will no need to change return type of funcn. & assign value of x to x😅 , I am leaving it for U to try ...
+ 7
Put your print statement in the addOneTo() method
public class MyClass {
public static void main(String[ ] args) {
int x = 5;
addOneTo(x);
}
static void addOneTo(int num) {
num = num + 1;
System.out.println(num);
}
}
+ 3
Sir D_Stark thanks for replying , but I just need to know why it returns 5 instead of 6 ?
+ 2
the method only manipulates the value of x but doesn't return the new value of x after manipulation. that's why you always get 5 instead of 6. therefore the method should be changed to have int as a return type to return the value. the returned value should also be saved in a variable in main so that you can print it to see the changes
+ 1
thanks a lot Gaurav Agrawal 😄
0
public class MyClass {
public static void main(String[ ] args) {
int x = 5;
System.out.println(addOneTo(x));
}
static int addOneTo(int num) {
int x = num;
x = x + 1;
return x;
}
}
I don't know Java, but this is how I got it to work. Lul
0
These 5-question are all very tricky, and what's more? The quiz creator actually uploads four version all looking very similar. So even if now in this version you understand why it's still. In next question, you may encounter the version same as DS, GA or DC's and the correct answer becomes 6.
So every time you have to work out the logic very carefully yourselves.
And the best way is to type the above codes into code playground and experiment little by little: what if i add static to int x? what if i do this? what if i do that?
only after a few experiments and understand all these changes, then you can dive back into the challenges, otherwise very easy to be tricked by a looks-alike version