Search code examples
javajava.util.scanner

How to answer a question with a string using the scanner class using java?


I have been trying all weekend to find a way to get my program to answer a question using a sting with a scanner class. For example I need to get my program to answer a question like

Who is on the 5 dollar bill?

Input would be Lincoln and other inputs would be invalid the question will have 3 choices so the logic has to work.

Can you point me in the right direction on how to get this to work in Java? I want to understand the material but I have really tried all weekend.


Solution

  • If I understood your question properly, then this should point you in the right direction:

    Import the Scanner:

    import java.util.Scanner;
    

    Then, here is the method you'd want to call:

    public void myScanner () {
         Scanner scan = new Scanner(System.in); //Creates a new scanner
         System.out.println("Who is on the 5 dollar bill?"); //Asks question
         String input = scan.nextLine(); //Waits for input
         if (input.equalsIgnoreCase("Lincoln")) { //If the input is Lincoln (or any case variant of Lincoln)
              System.out.println("Correct!");
         }
         else { //If the input is anything else
              System.out.println("Incorrect!");
         }
    }