Not sure if I am wording this correctly however I'm trying to get an input from a user which then checks if the answer is 'yes', and if it is I want it to return 'true', then use this in my main method.
[Main Method]
String inputFromUser = JOptionPane.showInputDialog(null, "Yes/No?");
checkBoolean(inputFromUser);
if(inputFromUser = true) {
System.out.println("Yes, true!"); }
else if(inputFromUser = false) {
System.out.println("No, false!"); }
public static boolean checkBoolean(String inputFromUser) {
boolean returnValue;
if(inputFromUser.equals("yes")) {
returnValue = true; }
else {
returnValue = false; }
}
return returnValue;
}
With this code I get incompatible types in my main method where I am doing inputFromUser = true. Required string but receives boolean.
error: incompatible types. if(inputFromUser = true) {
required: String
found: boolean
How can I make this work exactly? There's probably an answer on this site already but I do not know how to word the question exactly.
Change
checkBoolean(inputFromUser);
if(inputFromUser = true) {
System.out.println("Yes, true!"); }
else if(inputFromUser = false) {
System.out.println("No, false!"); }
to
if(checkBoolean(inputFromUser)) //This is same as if(checkBoolean(inputFromUser)==true)
System.out.println("Yes, true!");
else
System.out.println("No, false!");
In your current code,you try to assign a String
to a boolean
which makes no sense. I think you meant ==
there as you want to compare them.But even if you change that,it is wrong as you compare a String
with a boolean
value. Another way would be t store the return value of the method in a boolean
variable and use it in the if
.The below code does that:
boolean check = checkBoolean(inputFromUser);
if(check) //This is same as if(check==true)
System.out.println("Yes, true!");
else
System.out.println("No, false!");
Also,your checkBoolean
method can be shortened into a single line using
return inputFromUser.equals("yes");