Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java looping 3 times before giving correct output

Tags:

java

loops


I'm making an application that quizzes you on politics or astronomy.

My problem is that when you say "politics" or you say "astronomy", it will ask you again 2 more times for your input, before giving the desired output of "test".

Here's the code:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        do {
            if (getAnswer().equalsIgnoreCase("neither")) {
                System.out.println("Please enter \'astronomy\' or \'politics\'.");
            }
        getAnswer();
        }
        while(getAnswer().equalsIgnoreCase("neither"));
    System.out.println("test");
    }
    public static String getAnswer() {
        Scanner quizType = new Scanner(System.in);
        System.out.println("Would you like to be quizzed on politics or astronomy?");
        String typeAnswer = quizType.next();
        if (typeAnswer.equalsIgnoreCase("politics")) {
            return "politics";
        }
        else if (typeAnswer.equalsIgnoreCase("astronomy")) {
            return "astronomy";
        }
        else {
            return "neither";
        }
    }
}

Any ideas?
Thanks

like image 837
Brian E. Avatar asked Apr 09 '26 02:04

Brian E.


1 Answers

There no need to getAnswer() 3 times, just getAnswer() into a String variable and you are good to go.

Like this:

public static void main(String[] args) {
        String answer = "";
        do {
            answer = getAnswer();
            if (answer.equalsIgnoreCase("neither")) {
                System.out.println("Please enter \'astronomy\' or \'politics\'.");
            }
        } while (answer.equalsIgnoreCase("neither"));
        System.out.println("test");
    }

    public static String getAnswer() {
        Scanner quizType = new Scanner(System.in);
        System.out.println("Would you like to be quizzed on politics or astronomy?");
        String typeAnswer = quizType.next();
        if (typeAnswer.equalsIgnoreCase("politics")) {
            return "politics";
        } else if (typeAnswer.equalsIgnoreCase("astronomy")) {
            return "astronomy";
        } else {
            return "neither";
        }
    }
like image 128
Shanu Gupta Avatar answered Apr 10 '26 16:04

Shanu Gupta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!