How can I check if strings put in by the user via scanner (the user can choose how many words he wants to type in) contain the same letters? Lets say the users types in the following 3 words:
race
bicycle
computer
Every word in this example contains 'e' and 'c'. How can I compare those strings and safe the result (e and c) in a new string?
public class Comparison {
public static void main(String[] args) {
String letters = "";
Scanner input = new Scanner(System.in);
System.out.println("How many words do you want to type in?:");
count = input.nextInt();
String[] words= new String[count];
for (int i = 0; i < words.length; i++) {
if (words[i].charAt(0) == words[j].charAt(0)) {
letters = letters + words[i].charAt(j);
}
}
}
There are several pieces needed here.
Get the words from the user with a scanner. You are not asking about that. The idea would be to prompt, read in the input, and generate an array of strings. One way to do that might be to use the split method. You were not asking about this part. You asked what to do with this string array once you had it. To test the other parts you could use args passed to main, then develop this piece.
A method to find the common letters between just two strings. You indicated that you had such a method working. So I am not going to share that. Let's just imagine it looked like:
/**
Method findCommonLetters
*
#param word1 first word
#param word2 second word
#return a string containing the common letters in the two words, no repeats
*/
public String findCommonLetters(String word1, String word2) {
//your code here
}
A way to take an arbitrary length array of strings and get the letters all have in common. That is what you were asking for. Here is a method that will do that assuming you have the method described in 2 working. The idea is to work through just 2 at a time and look for only those letters in common in all the words so far in the next word (and loop until we have processed all the words). Code follows:
/**
Method findCommonLetters
*
#param words An array of words
#return A String containing the letters to all the words
*/
public String findCommonLetters(String[] words)
{
if (words.length == 0) {
return ""; //there are no letters
} else if (words.length == 1) {
//if the desired behavior is as I do here, this else if block could go away
return words[0]; //trivially all the words have the same letters
} else {
String result = words[0]; // first word
for (int i = 1; i < words.length; i++) {
result = findCommonLetters(result, words[i]); //find letters in common between all words processed so far and next word
//if you want, you could break here if result is empty
}
return result;
}
}
Putting together these three pieces will give the desired result.
Related
My program has a String inputted Eg. hello i am john who are you oh so i see you are also john i am happy
my program then has a keyword inputted Eg. i (the program doesn't like capitals or punctuation yet)
then it reads the initial String and finds all the times it mentions the keyword + the word after the keyword, Eg. i am, i see, i am.
with this is finds the most common occurrence and outputs that second word as the new keyword and repeats. this will produce
i am john/happy (when it comes to an equal occurrence of a second word it stops (it is meant to))
What i want to know is how i find the word after the keyword.
package main;
import java.util.Scanner;
public class DeepWriterMain {
public static void main(String[] args) {
String next;
Scanner scanner = new Scanner(System.in);
System.out.println("text:");
String input = scanner.nextLine();
System.out.println("starting word:");
String start = scanner.nextLine();
input.toLowerCase();
start.toLowerCase();
if (input.contains(start)) {
System.out.println("Loading... (this is where i find the most used word after the 'start' variable)");
next = input.substring(5, 8);
System.out.println(next);
}else {
System.out.println("System has run into a problem");
}
}
}
If you use split to split all your words into an array, you can iterate through the array looking for the keyword, and if it is not the last in the array, you can print the next word
String arr [] = line.split(" ");
for (int i = 0; i < arr.length -1; i++) {
if (arr[i].equalsIgnoreCase(keyword)) {
sop(arr[i] + " " arr[i + 1]);
}
if it is not the last in the array, iterate only to length - 1
The String class includes a method called public int indexOf(String str). You could use this as follows:
int nIndex = input.indexOf(start) + start.length()
You then only need to check if nIndex == -1 in the case that start is not in the input string. Otherwise, it gets you the position of the first character of the word that follows. Using the same indexOf method to find the next space provides the end index.
This would allow you to avoid a linear search through the input, although the indexOf method probably does one anyway.
I need to read the user input and compare this to a dictionary.txt. The user may input any number of characters and the program must return all the words in the English language that can be made from these characters. The letters can be used in any order and may only be used once.
For example:
User Input: "odg"
Output: "dog" , "god" ... and any others
After quite a substantial amount of research, I have come up with the following partial solution:
Read user input
Convert to an array of characters
Loop through the document depending on array length
Using indexOf to compare each character in this array to each line, then printing the word/s which do not return -1
How do I compare a set of characters inputted by the user to those found in a text file (dictionary) ? The characters do not have to be in any order to match .(as seen in the example used above)
Bear with me here, I know this must be one of the most inefficient ways to do such a task! Any further ideas on how to implement my original idea would be appreciated, while I am also open to any new and more efficient methods to perform this operation.
Below is what I have come up with thus far:
public static void main(String[] args) throws FileNotFoundException {
BufferedReader reader1 = new BufferedReader(new FileReader(FILENAME));
Scanner sc = new Scanner(System.in);
String line;
ArrayList<String> match = new ArrayList<>();
System.out.println("Enter characters to see which english words match: ");
String userInput = sc.next();
char arr[] = userInput.toCharArray();
int i;
try {
while ((line = reader1.readLine()) != null) {
for (i=0; i < arr.length; i++)
{
if ((line.indexOf(userInput.charAt(i)) != -1) && (line.length() == arr.length)) {
match.add(line);
}
else {
// System.out.println("no matches");
}
}
}
System.out.println(match);
}
catch (IOException e) {
e.printStackTrace();
}
**Current results: **
Words in text file:
cab
dog
god
back
dogs
quick
User input: "odg"
Program output:
[god, god, god, dog, dog, dog]
The program should return all words in the dictionary that can be made out of the string entered by the user I am managing to return both instances in this case, however, each are displayed for three times (arr.length).
First of all, interesting question. I implemented my solution and Ole V.V's solution. Here are the codes based on your post. I test the only test case you provided, not sure whether this is what you want. Let me know if it is not working as you expected.
Solution One: counting O(nk)
public static void main(String[] args) throws IOException {
BufferedReader reader1 = new BufferedReader(new FileReader(FILENAME));
Scanner sc = new Scanner(System.in);
System.out.println("Enter characters to see which english words match: ");
String userInput = sc.next();
Map<Character, Integer> counter = count(userInput);
String line;
while ((line = reader1.readLine()) != null) {
Map<Character, Integer> lineCounter = count(line);
if(lineCounter.equals(counter)) {
System.out.println(line);
}
}
}
public static Map<Character, Integer> count(String input) {
Map<Character, Integer> result = new HashMap<Character, Integer>();
for (char c: input.toCharArray()) {
result.putIfAbsent(c, 0);
result.put(c, result.get(c) + 1);
}
return result;
}
Solution Two: sorting O(nk)
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(FILENAME));
Scanner sc = new Scanner(System.in);
System.out.println("Enter characters to see which english words match: ");
String userInput = sc.next();
userInput = sort(userInput);
String line;
while ((line = reader.readLine()) != null) {
String sortedLine = sort(line);
if(sortedLine.equals(userInput)) {
System.out.println(new String(line));
}
}
}
// counting sort
public static String sort(String input) {
char c[] = input.toCharArray();
int length = c.length;
char output[] = new char[length];
int count[] = new int[256];
for (int i = 0; i < length; i++) {
count[c[i]] = count[c[i]] + 1;
}
for (int i = 1; i <= 255; i++) {
count[i] += count[i - 1];
}
for (int i = 0; i < length; i++) {
output[count[c[i]] - 1] = c[i];
count[c[i]] = count[c[i]] - 1;
}
return new String(output);
}
The standard solution to this kind of problem is: sort the characters of the user input. So odg will become dgo and back will become abck. For each word in the dictionary, do the same sorting. So cab will become abc and dog will be dgo — hey, that’s the same as the first user input, so now we know that this word should be output.
The strong point with this solution is you make sure every letter is used exactly once. It even takes duplicate letters into account: if the same letter comes twice in the user input, it will only find words that also contain that letter exactly twice.
If you like, you can prepare your word list in advance by building a map where the keys are the alphabetically sorted words and the values are lists of words that contain those same letters. So key dgo will map to a list of [dog, god]. Then you just have to sort the input and make a lookup.
I'll show you a solution that is easy to understand and implement but not the fastest available:
Possible solution: Array sorting
Treat input string and dictionary word as array of chars, sort them, then compare them:
public static boolean stringsMatchSort(String a, String b) {
// Different length? Definitely no match!
if (a.length() != b.length()) {
return false;
}
// Turn both Strings to char arrays
char[] charsA = a.toCharArray();
char[] charsB = b.toCharArray();
// Sort both arrays
Arrays.sort(charsA);
Arrays.sort(charsB);
// Compare them, if equal: match!
return Arrays.equals(charsA, charsB);
}
Note how I made the meat of your program / problem into a method. You can then easily use that method in a loop that iterates over all words of your dictionary. The method doesn't care where the words come from: a file, a collection, additional user input, the network, etc.
It also helps to simplify your program by dividing it into smaller parts, each with a smaller responsibility. This is commonly known as divide & conquer and is one of the most valuable strategies for both, new and old programmers alike, when it comes to tackling complicated problems.
Other solutions: Prime numbers, HashMaps, ...
There are other (including faster and more elegant) solutions available. Take a look at these related questions, which yours is pretty much a duplicate of:
"How to check if two words are anagrams"
"finding if two words are anagrams of each other"
Additional notes
Depending on your application, it might be a good idea to first read the dictionary into a suitable collection. This would be especially helpful if you perform multiple "queries" against the same dictionary. Or, if the dictionary is really huge, you could already strip out duplicates during the creation of the collection.
Hello I am working on an assignment and I'm running into issues I was hoping for a little direction...
The purpose is to have user input a phrase and create an acronym out of that phrase. Anything over three words will be ignored.
I'm having issues with the acronym part, I am able to get the first character and figured that I would loop through the user input and grab the character after a space, but that is not working. All I am getting is the first character, which is obvious because I grab that first, but I can't figure out how to "save" the other two characters. Any help is greatly appreciated.
*********UPDATE************************
So thanks to an answer below I have made progress with using the StringBuilder. But, now if I enter "Your Three Words" the Output is: YYYYYTYYYYYWYYYY
Which is progress but I can't understand why it's repeating those first characters so many times??
I edited the code too.
*********UPDATE*****************************
public class ThreeLetterAcronym {
public static void main(String[] args) {
String threeWords;
StringBuilder acronym = new StringBuilder();
Scanner scan = new Scanner(System.in);
System.out.println("Enter your three words: ");
threeWords = scan.nextLine();
for(int count = 0; count < threeWords.length(); count++) {
acronym.append(threeWords.charAt(0));
if(threeWords.charAt(count) == ' ') {
++count;
acronym.append(threeWords.charAt(count));
}
}
System.out.println("The acronym of the three words you entered is: " + acronym);
}
}
You can't save the other characters because char is supposed to store only one character.
You can use a StringBuilder in this case
StringBuilder acronym = new StringBuilder();
Then in your loop simply replace it with
String[] threeWordsArray = threeWords.split(" ");
for(String word : threeWordsArray) {
acronym.append( word.substring(0, 1) );
}
**updated
You store the character at the current index in space:
char space = threeWords.charAt(count);
Then you compare the value of space with the integer value 3:
if(space < 3)
This will almost certainly never be true. You are asking for the numeric value of a character. Assuming it is a letter it will be at least 65. I suspect that your intention is to store something different in the variable space.
Not exactly sure how to phrase this question.
I'm writing a spell check program, that reads words from a text file. These words are then added to an ArrayList of type:
ArrayList<String> dictionaryList = new ArrayList<String>();
Now, the program runs as an endless loop (until 'q' is typed), and the user is prompted to search for a word. If the word can be found, the program returns a simple "Found word" message.
Otherwise; take the search term and generate variations of that word. These variations are added to the list:
ArrayList<String> allSimilarWords = new ArrayList<String>();
For instance, the word "coffei" would generate a series of "similar words", one of them being "coffee" (a word in the English language).
Now, seeing that I have both a list of all the dictionary words, as well as a list of the similar words, the program checks if words in allSimilarWords are contained in dictionaryList.
I have checked my generateSimilarWords-method, and it works as expected.
However, there is a problem when asking for user input the second time. The first time (typing "coffei" (where coffee is in the dictionary list)), the program produces the following output:
Enter search term:
coffei
Suggestion for similar words:
-coffee
Since this is an endless loop, the program asks me to enter another word. Now, if I type "banaan" (where banana is in the dictionary), the program produces the following output:
Enter search term:
banaan
Suggestion for similar words:
-coffee
-banana
Hence, it "remembers" me searching for coffei, and provides "coffee" as a suggested word, in addition to the word "banana". I've been trying to figure out why this happens, but cannot find my error. Any help would be highly appreciated. Following is the code:
CODE
//GETTING SIMILAR WORD ARRAYLIST
public ArrayList<ArrayList<String>> getSimilarWords(String searchWord) {
this.searchWord = searchWord;
char[] wordAsCharacterArray = searchWord.toCharArray(); //Convert search String to a character array
//Call helper methods to add the suggested similar words to the similarWordArrayList
similarWordArrayList.add(charSwap(wordAsCharacterArray)); //Add swapped character suggestions
similarWordArrayList.add(charRemove(wordAsCharacterArray)); //Add removed character suggestions
similarWordArrayList.add(charAdd(wordAsCharacterArray)); //Add removed character suggestions
similarWordArrayList.add(charReplace(wordAsCharacterArray)); //Add removed character suggestions
return similarWordArrayList;
}
The similarWordArrayList is later "converted" to an ArrayList containing only String elements, as opposed to being a list of type ArrayList < ArrayList< String > >.
//Method to generate and suggest similar words
private void suggestWords(ArrayList<ArrayList<String>> similarWords) {
allSimilarWords = convertSingleList(similarWords);
String currWord = "";
outer: for(int i = 0; i < allSimilarWords.size(); i++) { //Iterate through the list of similar words
currWord = allSimilarWords.get(i); //Set current similar word to a String variable
for(int j = 0; j < i; j++) {
if(currWord.equalsIgnoreCase(allSimilarWords.get(j))) {
continue outer;
}
}
if(myDictionaryList.contains(currWord)) {
System.out.println("-" + currWord);
}
}
}
Method for finding the String:
public void findString(String word) {
searchTerm = word;
if(myDictionaryList.contains(word)) { //If found
System.out.println("Found word!"); //Notify
}
else {
//Find all similar words
System.out.println("Suggestions for similar words: ");
similarWords = handler.getSimilarWords(searchTerm);
suggestWords(similarWords);
}
}
Any help on how I can fix this, so that the program only prints out suggested words based on the LAST search term (and not remembering previously suggested words), is highly appreciated.
I think, the first thing, you have to do is to clear your arraylist before adding words to it.
//GETTING SIMILAR WORD ARRAYLIST
public ArrayList<ArrayList<String>> getSimilarWords(String searchWord) {
this.searchWord = searchWord;
char[] wordAsCharacterArray = searchWord.toCharArray(); //Convert search String to a character array
//Clear the list before adding words
similarWordArrayList.clear();
//Call helper methods to add the suggested similar words to the similarWordArrayList
similarWordArrayList.add(charSwap(wordAsCharacterArray)); //Add swapped character suggestions
similarWordArrayList.add(charRemove(wordAsCharacterArray)); //Add removed character suggestions
similarWordArrayList.add(charAdd(wordAsCharacterArray)); //Add removed character suggestions
similarWordArrayList.add(charReplace(wordAsCharacterArray)); //Add removed character suggestions
return similarWordArrayList;
}
I'm currently doing an exercise(not homework before anyone gives out) and I am stuck in the final part of the question.
The question is:
Write a program which will input a String from the keyboard, output the number of
seperate words, where a word is one or more characters seperated by spaces. Your
program should only count words as groups of characters in the rang A..Z and a..z
I can do the first part no problem as you can see by my code:
import java.util.Scanner;
public class Exercise10 {
public static void main(String[] args) {
String input;
int counter = 0;
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter your text: ");
input = keyboard.nextLine();
for(int i = 0; i < input.length(); i++){
if(input.charAt(i) == ' '){
counter++;
}
}
System.out.println(counter + 1);
keyboard.close();
}
}
However the part that is confusing me is this:
Your program should only count words as groups of characters in the rang A..Z and
a..z
What should I do in this instance?
I won't give you a full answer but here are two hints.
Instead of counting spaces look at splitting the string and looping through each element from the split:
Documentation
Once you have the String split and can iterate through the elements, iterate through each character in each element to check if it is alphabetic:
Hint
I believe it should not consider separate punctuation characters as words. So the phrase one, two, three ! would have 3 words, even if ! is separated by space.
Split the string on spaces. For every token, check the characters; if at least one of them is in range a..z or A..Z, increment counter and get to the next token.