java - How do I pass a Boolean value between classes and get the desired Output -
i having 2 class hello.java
class hello { private boolean check ; public hello() { } void display() { if(check == true) { system.out.println("available"); } else if(check == false) { system.out.println("not availabe"); } } }
and main.java
public class main { public static void main(string[] args) { scanner sc = new scanner(system.in); boolean check; system.out.println("is available(yes/no):"); string av = sc.nextline(); if(av.equals("yes")) { check = true; } else if(av.equals("no")) { check = false; } hello hello=new hello(); hello.display(); } }
i want if input "yes" "available" output simmilarly when input "no" "not available". value must pass through hello class output. getting "not available" output every time. how can solve it??
pass check value in constructor of hello
class hello { //check in hello class private boolean check; //#1 //constructor take check input public hello(boolean check) { this.check = check } void display() { if(check) { system.out.println("available"); } else { system.out.println("not availabe"); } } }
now create object of hello class boolean value.
public class main { public static void main(string[] args) { scanner sc = new scanner(system.in); //this check different hello class check //check in main class boolean check; //#2 system.out.println("is available(yes/no):"); string av = sc.nextline(); if(av.equals("yes")) { check = true; } else if(av.equals("no")) { check = false; } hello hello=new hello(check); hello.display(); } }
you have 2 check variables (see comment in code #1 , #2). both has nothing each other, both different. #1 instance variable of class hello , #2 local variable of main method.
wiki
Comments
Post a Comment