Using an if statement with a system.in scanner

2.4k views Asked by At

I'm not sure how to explain this problem but please someone help me. I want to have a program to where if a word is typed into the keyboard, I have an if statement that makes it so that when that word is entered it prints out a sentence on the screen. Like, if I typed in "dog" and hit enter the screen would display information on dogs or something.

3

There are 3 answers

0
Abhijeet Dhumal On

To achieve this functionality, if you don't have much entries you can use Hashmap to store your keys as word and its detailed information as values. When user enters word for search, you can search it out in map.

Please see the following example for single word search:

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

public class SearchText {

  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    HashMap wordMap = new HashMap();
    wordMap.put("Dog", "Dog is a nice pet");
    wordMap.put("Cat", "Cat is a beautiful pet");

    System.out.println("please enter a word: ");
    String inputWord = input.nextLine();

    if (wordMap.containsKey(inputWord)){
        System.out.println("Key: " + inputWord + ": " + wordMap.get(inputWord));
    } else {
        System.out.println("Please enter correct word");
    }
  }

}

If you have huge data, you can store it in any database table and whenever user enters the keyword, you can search the database using query for keyword and return result as needed.

0
austin wernli On

You could use the Scanner to gather input from the keyboard, and then have an if statement to decide if the inputted string matches any string you want to present information about.

public void awesome(){
        Scanner scannerMcgee = new Scanner(System.in);
        String input = scannerMcgee.nextLine();
        if(input.equalsIgnoreCase("dog"))
            System.out.println("Information magically displays about " + input);
    }
0
Robert On

I'm a bit confused about what you want. Here is the first part of the solution to your problem.

import java.util.Scanner;

public class DogClass {
         public static void main(String[] args){
                Scanner input = new Scanner(System.in);
                System.out.println("please enter a word");
                String dogType = input.nextLine();
                System.out.println("the thing you chose was " + dogType);   
         }
}

The problem will ask you to enter a word and then the word will be printed. Please explain your problem further.