Wai Loon II
Wai Loon II

Reputation: 259

how to i input a sentence so that the program will recognize the sentence as a single word?

lets say i input : 'dog is mammal'

i would like to search for this sentence in a text document. How do i do this in java ?

    System.out.println("Please enter the query  :");
    Scanner scan2 = new Scanner(System.in);
    String word2 = scan2.nextLine();
    String[] array2 = word2.split(" ");

this code snippet accepts the string 'dog is mammal' and process each tokens separately.

For example : 'dog is mammal'

dog

>

>

is

>

>

mammal

>

>

i would like to process the input as

dog is mammal

>

>

I doesnt want it to process it separately. I wanted it to process it as a single string and look for matches. Can anyone let me know where i am lacking ?

Upvotes: 0

Views: 17043

Answers (3)

Peter Lawrey
Peter Lawrey

Reputation: 533560

If you want to process the String as a single piece of text, why split up the string into words. I would just use the original word2 you have which is the whole text AFAICS

EDIT: If I run

System.out.println("Please enter the query  :");
Scanner scan2 = new Scanner(System.in);
String word2 = scan2.nextLine();
System.out.println(">"+word2+"<");

I get

Please enter the query  :
dog is mammal
>dog is mammal<

The input is not broken up by word.

Upvotes: 3

bezmax
bezmax

Reputation: 26142

Simply concatinate them all while reading:

public String scanSentence() {
    Scanner scan2 = new Scanner(System.in);
    StringBuilder builder = new StringBuilder();
    String word2;
    //I do not know how you want to terminate input, so let it be END word.
    //If you will be reading from file - change it to "while ((word2 = scan2.nextLine()) != null)"
    //Notice the "trim" part
    while (!(word2 = scan2.nextLine().trim()).equals("END")) { 
        builder.append(word2);
        builder.append(" ");
    }

    return builder.toString().trim();
}

Upvotes: 0

Nirmal- thInk beYond
Nirmal- thInk beYond

Reputation: 12054

find word2 directly in file, and if you has parsed whole file then use string indexof(word2) in file

Upvotes: 0

Related Questions