0

Help! How do i get a word that appear before and after a particular word in java

example is " I love java". I want to get ( I & java) in an HashSet

12th Nov 2017, 1:16 AM
Osahon Terry Ewere
Osahon Terry Ewere - avatar
1 Réponse
+ 4
I'm not really sure how you wanted to go about this, but this code will take a sentence string in, break each word into an array, and then take in a word to check for in the string. If the word is the first word then there is no word before it and if the word is the last word none after. The before and after words are inserted into a string array with only 2 elements each initialized to an empty string. This array is then converted into a hashset. The contents of the hashset is then output. @Jonathan, Remember that a set is not indexed nor is it ordered. There isn't a get() method for a HashSet. If there were a get() method using get(0) could return any object within the Set as they aren't ordered. https://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html import java.util.Scanner; import java.util.Set; import java.util.HashSet; import java.util.Arrays; public class Program { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter a sentence to check: "); String[] input = sc.nextLine().trim().split(" "); System.out.println("Enter word to check for: "); String match = sc.nextLine().trim(); String[] surroundingWords = new String[2]; surroundingWords[0] = ""; surroundingWords[1] = ""; for(int i = 0; i < input.length; ++i) { if(input[i].toLowerCase().equals(match.toLowerCase())) { if(i == 0) { surroundingWords[1] = input[i+1]; break; } else if (i == input.length - 1) { surroundingWords[0] = input[i-1]; break; } else { surroundingWords[0] = input[i-1]; surroundingWords[1] = input[i+1]; break; } } } Set<String> wordSet = new HashSet<String>(Arrays.asList(surroundingWords)); for(String word: wordSet) { System.out.println(word); } } }
12th Nov 2017, 2:31 AM
ChaoticDawg
ChaoticDawg - avatar