dimanche 13 janvier 2019

Im using IF-ELSE statements and it is not working like it should

I have a program that uses if loops to test the ending and beginning of a sentence, i am fairly new to coding and this is being weird first of all here's my class

if i type "Who?" "what?" and the rest by themselves with a question mark the code works fine,

but if i ask a question in a sentence, starting with either who what where why when and ending with a question mark, it doesn't work normally. it spits out the else statement at the end there, but it shouldnt? because i have it set to if it ends with a question mark do that, if it doesnt then spit out that its not a question. overall the code is being weird with other stuff can anyone help me out tell me whats going on what needs to be fixed?

import java.util.Scanner;

public class Answers {

static Scanner sc = new Scanner(System.in);

public static void main(String[] args) {
    begin();

}

public static void begin() {

    System.out.println("Ask me a question!");
    String question = sc.next();

    if(question.endsWith("?")) {

        if(question.startsWith("who")) {
            System.out.println("Lyon Mackenzie King.");
        } 

        if(question.startsWith("what")) {
            System.out.println("The Higgs boson.");
        } 

        if(question.startsWith("when")) {
            System.out.println("Right now!");
        }

        if(question.startsWith("where")) {
            System.out.println("Here.");
        }

        if(question.startsWith("why")) {
            System.out.println("Why not?");
        }

        if(!question.startsWith("who") && !question.startsWith("what") && !question.startsWith("when") && !question.startsWith("where") && !question.startsWith("why")) {
            System.out.println("That is one of the great mysteries of the universe.");
        }

    } else {
        System.out.println("That doesnt sound like a question to me..");
    }

} 

}

Aucun commentaire:

Enregistrer un commentaire