+ 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());}}
5 Respostas
+ 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;
}
+ 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.
+ 2
The code is truncated, better save it as code bit and share its link in post Description.
0
A͢J why is it called local. Is color or c local
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.