mercredi 13 février 2019

Converting String input from Scanner to boolean ("yes" to true, "no" to false)

I wrote a simple program that asks the user to enter "yes" or "no". I store that input to a String using a Scanner. I also have a boolean set to false.

I then use an if statement to check the user's input and assign a corresponding value to the boolean. If the user entered "yes", then the boolean is set to true and vice-versa.

Next, I print the boolean. Every time I run the program the boolean stays as false and the if statement defaults to my last else block, which prints a String that reads "error".

I tried doing this without the Scanner and simply set the String to "yes" or "no" within the code. It worked just fine and the if statement changed the value of the boolean and printed it correctly. This may work, but this is not what I want the program to do. I would like it to accept the user's input for the String.

import java.util.Scanner;
public class StringToBoolean {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Please enter yes or no");
        String yesOrNo = input.nextLine();
        boolean trueOrFalse = false;
        if (yesOrNo == "yes") {
            trueOrFalse = true;
        } else if (yesOrNo == "no") {
            trueOrFalse = false;
        } else {
            System.out.println("Error");
        }

        System.out.println(trueOrFalse);
    }
}

I'm not sure why this is happening, but it appears to be an issue with the Scanner. Please let me know if there is a way to accept String values with a Scanner and then use the input to set the value of a boolean. Thank you.

Aucun commentaire:

Enregistrer un commentaire