Java – compare string input

import java.util.Scanner;
import java.util.Scanner;

public class TrueFalseQuiz {

    public static void main(String[] args) {
        Scanner myScanner = new Scanner(system.in);
        String youranswer;

        boolean answer = false;
        System.out.print("The queens name is Elizabeth? yes or no ");
        youranswer = myScanner.toString();

        String start = myScanner.next();

        {
            if (youranswer.equals("yes")) {
                answer = true;
            }
        }

        if (answer == true) {
            System.out.println("Answer is correct");
        } else {
            System.out.println("Answer is wrong");
        }
    }
}

This code does not seem to compare the input with the string I want ("yes" or "no") I'm a beginner. This is just the basic code I'm playing

Solution

So, you have a few things here:

>You want to use scanner Next() or scanner Nextline() retrieves input from the end user. > You want to get rid of static code blocks around if statements. > You want to compare the answers to any case - if I type "yes", it will fail You can change it to:

answer = "yes".equalsIgnoreCase(youranswer);

Since it is a Boolean value, if the value is true, there is no need to compare and set the variable to true You can set it explicitly. > In the last block, you do not need to compare with true in Boolean values You can simply say no (answer)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>