+ 1

It is successfully Compiled but The Result is null. Why

import java.util.Scanner; public class Main{ private String color; String power; int num; Main(String c){color=c;} public void setColor(String c){this.color=c; } public String getColor(){if (num==8){ return color;} else {return power;}} public static void main(String[]args){ Scanner Obj= new Scanner(System.in); int num=Obj.nextInt(); String power="power"; String color="color"; Main v=new Main(color); System.out.println(v.getColor());}}

9th Mar 2023, 8:05 AM
We Doru
We Doru - avatar
5 odpowiedzi
+ 2
Because "num" and "power" are local variable and you didn't initialised them in constructor You should do this: Main(String c, int num, String power){ this.color=c; this.num = num; this.power = power; }
9th Mar 2023, 9:26 AM
A͢J
A͢J - avatar
+ 3
One possible problem with your code is that you are using a local variable num in your main method, which is different from the instance variable num in your Main class. The local variable num is not visible to the getColor() method, so it will always return power. You may want to use this.num = Obj.nextInt(); instead of int num = Obj.nextInt(); to assign the user input to the instance variable.
9th Mar 2023, 8:12 AM
Minh Lưu
Minh Lưu - avatar
+ 2
The code is truncated, better save it as code bit and share its link in post Description.
9th Mar 2023, 9:20 AM
Ipang
0
A͢J why is it called local. Is color or c local
9th Mar 2023, 12:53 PM
We Doru
We Doru - avatar
0
A͢J this does work too,,, color=c;num=n , instead of this.color or this.num But the reason why this syntax work is still not known.May be it just work like that by rule.
9th Mar 2023, 2:16 PM
We Doru
We Doru - avatar