Why x does not equal 6 | Sololearn: Learn to code for FREE!
Nouvelle formation ! Tous les codeurs devraient apprendre l'IA générative !
Essayez une leçon gratuite
0

Why x does not equal 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; } }

29th Jan 2019, 5:33 PM
Tarik Khalil
Tarik Khalil - avatar
3 Réponses
+ 4
You did not return the value in the method addOne and assign the result back in the main method. If you return the value, change the return value of addOne to int instead of void. If you don't want to create a new variable to receive the result from addOne, you can just print it immediately: System.out.println(addOneTo(x));
29th Jan 2019, 5:44 PM
Lambda_Driver
Lambda_Driver - avatar
+ 4
In your case you have to return num + 1: public class MyClass { public static void main(String[ ] args) { int x = 5; x = addOneTo(x); System.out.println(x); } static int addOneTo(int num) { return num + 1; } }
29th Jan 2019, 5:45 PM
Denise Roßberg
Denise Roßberg - avatar
+ 3
Another example: public class Num { public int x; public void addOneTo(int x) { this.x = x + 1; //the public int x = x from your method + 1 } } public class Program { public static void main(String[] args) { int a = 5; //create a object of Num Num number = new Num(); number.addOneTo(a); System.out.println(number.x); } } In this case you have a class Num with the public int x and the method addOneTo (int x) If you call the method, for example addOneTo (5) you change the public int x inside your class Num. I
29th Jan 2019, 6:11 PM
Denise Roßberg
Denise Roßberg - avatar