Need some help on managing Strings - java

Don't worry about the hash table guys but just give me some idea how to manage Strings.
I need to do spell check a word entered by the user in dictionary using hashtables. I got a method named checkDictionary() from hash tables to check whether the given word is present in dictionary or not. It returns a Boolean value if the word is present or false if not.
What I want to do is, I just want to check the word in dictionary when it is misspelled, making some possible corrections.
possible corrections :
Change one letter: For example, if the misspelled word is “kest”, i want to try all possibilities of
changing one character at a time, and look the modified word up in the dictionary. The
possibilities will be “aest”, “best”,...,”zest”, “kast”,...,”kzst”, etc.
---How can I change a single character at a time and that too from a to z.
Exchange adjacent letters: For example, if the misspelled word is “ebst”, try “best”, esbt”
and “ebts”.
---How can I change the adjacent letters , need to swap or something?..
Remove one letter: For example, if the misspelled word is
“tbird”, try all possibilities of removing one letter at a time, and look the modified word up
in the dictionary, which are: “bird”, “tird”, “tbrd”, and “tbir”.
---How can I remove each letter every time?
Please do remember that the word entered may be of any length.
I need to return this suggestions to the user after checking the words in dictionary.
Is there any methods in Strings that I can use to implement these functions.
Please help in implementing the above methods Change, Exchange and Remove.
import java.util.*;
import java .io.*;
public class HashTableDemo
{
public static void main(String [] args)
{
// constructs a new empty hashtable with default initial capacity
HashTable hashtable = new HashTable();
Scanner keyboard = null;
Scanner input=null;
try
{
System.out.println("Enter a word to check in dictionary");
keyboard = new Scanner(System.in);
String word = (keyboard.nextLine().toUpperCase());
//Adding aal dictionary words from a text file to hash table.
input=new Scanner(new FileInputStream("TWL.txt"));
int i=1;
// adding value into hashtable
while(input.hasNextLine())
{
String hello = input.nextLine();
hashtable.put( hello, new Integer(i) );
i++;
}
);
if(hashtable.checkDictionary(word))
System.out.println("The word "+word+" is there in the dictionary.");
else
System.out.println("The word "+word+" is not there in the dictionary.");
}//try
//Here I need to implement the required methods if the word is not in dictionary and misspelled.
catch(FileNotFoundException e)
{
System.out.println("Cannot open file");
System.exit(0);
}//end catch

There is no simple solution for what you're trying to accomplish. A good mathematical concept you could use for spell-checking is called Edit Distance, you should definitely read a bit of theory before attempting to write some code.

Related

How to find strings within a text file in JAVA

I'd like to just see an example with some explanation.
What string functions do I use to compare the objects and does it compare each character or the actual word without any additional letters to it?
Thanks
I tried doing something very similar to this question for a project awhile ago. There are numerous ways to do this in Java, but I used the Scanner class and the File class.
public static void main(String[] args)
{
Scanner input = new Scanner(System.in); //Just a normal scanner
System.out.println("Please enter in the pathname to the file you want to view.");
String pathname = input.nextLine(); //Pathname to text file
File book = new File(pathname); //Creating a new file using the pathname
if(book.canRead() == false) //If Java cant read the file, this will pop up
{
System.out.println("Your file cannot be read");
}
else if(book.canRead() == true) //If Java can read the file, then this asks for the word to search for
{
System.out.println("Please enter in the word you wish to search for.");
wordToSearchFor = input.nextLine();
wordCounter(book); //Calls the method
}
System.out.println(wordToSearchFor.toLowerCase() + " appeared " + numOfOccurrences + " times in " + pathname);
}
This is the main method where you use the File class to create a file based off of a pathname that you give it EX - C:\Users\alex\Downloads\mobydick.txt
I then check to see if you can read the file, and if you can, then I call a method to analyze the book itself
import java.io.*;
import java.util.Scanner;
public class TextReader
{
private static int numOfOccurrences; //Counter to keep track of the number of occurances
private static String wordToSearchFor; //String field so both methods can access it
/*
* This method takes in the file of the book so the scanner can look at it
* and then does all of the calculating to see if the desired word appears,
* and how many times it does appear if it does appear
*/
public static void wordCounter(File bookInput)
{
try
{
Scanner bookAnalyzer = new Scanner(bookInput); //Scanner for the book
while(bookAnalyzer.hasNext()) //While the scanner has something to look at next
{
String wordInLine = bookAnalyzer.next(); //Create a string for the next word
wordInLine = wordInLine.toLowerCase(); //Make it lowercase
String wordToSearchForLowerCase = wordToSearchFor.toLowerCase();
String wordToSearchForLowerCasePeriod = wordToSearchForLowerCase + ".";
if(wordInLine.indexOf(wordToSearchForLowerCase) != -1 && wordInLine.length() == wordToSearchFor.length())
{
numOfOccurrences++;
}
else if(wordInLine.indexOf(wordToSearchForLowerCasePeriod) != -1 && wordInLine.length() == wordToSearchForLowerCasePeriod.length())
{
numOfOccurrences++;
}
}
}
catch(FileNotFoundException e) //Self explanitory
{
System.out.println("The error is FileNotFoundException - " + e);
System.out.println("This should be impossible to get to because error checking is done before this step.");
}
}
Scanners in Java can be take a File object to analyze, which is the fist thing I do in this method. I then use a while loop and ask the Scanner if there is a word that follows the current word. As long as there is a word, this will continue to run. I then create a String of the current word that the scanner is on to use as a reference to compare against. I then use a method that comes with the String class to make everything lowercase because uppercase and lowercase letters matter.
The first if statement in this method checks if the current word that the scanner has matches what you are searching for using the indexOf method from the String class, which takes some string and looks to see if it exists in another string. The if statement comparison also makes sure that the desired word length is the same as the word length in the book in case you are looking up "the" and it doesnt mark "then" as a word since it contains "the". The second if statement does the same thing, just with your desired word with a period at the end. If you wanted to go the extra mile, you could also check for exclamation points, question marks, commas, and so forth, but I decided to just check for periods.
Every time one of these if statements is correct, I increment a variable by one, and after the scanner runs out of words to search for, I print out the total number of times that certain word appears in a text file.

print even words from string input?

I am in a beginners course but am having difficulty with the approach for the following question: Write a program that asks the user to enter a line of input. The program should then display a line containing only the even numbered words.
For example, if the user entered
I had a dream that Jake ate a blue frog,
The output should be
had dream Jake a frog
I am not sure what method to use to solve this. I began with the following, but I know that will simply return the entire input:
import java.util.Scanner;
public class HW2Q1
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a sentence");
String sentence = keyboard.next();
System.out.println();
System.out.println(sentence);
}
}
I dont want to give away the answer to the question (for the test, not here), but I suggest you look into
String.Split()
From there you would need to iterate through the results and combine in another string for output. Hope that helps.
While there will be more simpler and easier way to do this, I'll use the basic structure- for loop, if block and a while loop to achieve it. I hope you will be able to crack the code. Try running it and let me know if there is an error.
String newsent;
int i;
//declare these 2 variables
sentence.trim(); //this is important as our program runs on space
for(i=0;i<sentence.length;i++) //to skip the odd words
{
if(sentence.charAt(i)=" " && sentence.charAt(i+1)!=" ") //enters when a space is encountered after every odd word
{
i++;
while(i<sentence.length && sentence.charAt(i)!=" ") //adds the even word to the string newsent letter by letter unless a space is encountered
{
newsent=newsent + sentence.charAt(i);
i++;
}
newsent=newsent+" "; //add space at the end of even word added to the newsent
}
}
System.out.println(newsent.trim());
// removes the extra space at the end and prints newsent
you should use sentence.split(regex) the regular expression is going to describe what separate your worlds , in your case it is white space (' ') so the regex is going to be like this:
regex="[ ]+";
the [ ] means that a space will separate your words the + means that it can be a single or multiple successive white space (ie one space or more)
your code might look like this
Scanner sc= new Scanner(System.in);
String line=sc.nextLine();
String[] chunks=line.split("[ ]+");
String finalresult="";
int l=chunks.length/2;
for(int i=0;i<=l;i++){
finalresult+=chunks[i*2]+" ";//means finalresult= finalresult+chunks[i*2]+" "
}
System.out.println(finalresult);
Since you said you are a beginner, I'm going to try and use simple methods.
You could use the indexOf() method to find the indices of spaces. Then, using a while loop for the length of the sentence, go through the sentence adding every even word. To determine an even word, create an integer and add 1 to it for every iteration of the while loop. Use (integer you made)%2==0 to determine whether you are on an even or odd iteration. Concatenate the word on every even iteration (using an if statement).
If you get something like Index out of range -1, manipulate the input string by adding a space to the end.
Remember to structure the loop such that, regardless of the whether it is an even or odd iteration, the counter increases by 1.
You could alternatively remove the odd words instead of concatenation the even words, but that would be more difficult.
Not sure how you want to handle things like multiple spaces between words or weird non-alphabetically characters in the entry but this should take care of the main use case:
import java.util.Scanner;
public class HW2Q1 {
public static void main(String[] args)
{
System.out.println("Enter a sentence");
// get input and convert it to a list
Scanner keyboard = new Scanner(System.in);
String sentence = keyboard.nextLine();
String[] sentenceList = sentence.split(" ");
// iterate through the list and write elements with odd indices to a String
String returnVal = new String();
for (int i = 1; i < sentenceList.length; i+=2) {
returnVal += sentenceList[i] + " ";
}
// print the string to the console, and remove trailing whitespace.
System.out.println(returnVal.trim());
}
}

Searching through a Hashset for words within a file

I've got a Hashset with my dictionary of words in it.
What I'm trying to do is to individually scan words from the file checkMe to see whether they exist in my HashSet.
When a word doesn't exist, I need to trigger a number of actions (which I won't get into).
For now, I'd like some advice as to how I take words from my scanned file and check them against my HashSet.
Something like:
if (dicSet does not contain a word in checkMe) {
da da da
}
Also, I want to be able to loop through checkMe to make sure each word is checked through dicSet until I reach an error.
My code so far:
import java.util.*;
import java.io.*;
public class spelling{
public static void main(String args[]) throws FileNotFoundException {
//read the dictionary file
Scanner dicIN = new Scanner(new File("dictionary.txt"));
//read the spell check file
Scanner spellCheckFile = new Scanner(new File("checkMe.txt"));
//create Hashset
Set <String> dicSet = new HashSet<String>();
//Scan from spell check file
Scanner checkMe = new Scanner(spellCheckFile);
//Loop through dictionary and store them into set. set all chars to lower case just in case because java is case sensitive
while(dicIN.hasNext())
{
String dicWord = dicIN.next();
dicSet.add(dicWord.toLowerCase());
}
//make comparisons for words in spell check file with dictionary
if(dicSet){
}
// System.out.println(dicSet);
}
}
while(checkMe.hasNext())
{
String checkWord = checkMe.next();
if (!dicSet.contains(checkWord.toLowerCase())) {
// found a word that is not in the dictionary
}
}
That's the basic idea at least. For real use, you'd have to add a ton of error-checking and exceptional states handling (what if your input contains numbers? What about ., - etc?)

Read words until user writes 'end', then, order lexicographically(as in a dictionary), show the last word

User will enter words until the last word written is "end", then the code has to order lexicographically, as we have in a dictionary, all the words entered before 'end' and print the last word, the one classified the last.
//.....
Scanner word = new Scanner (System.in);
String keyword="end";
String finalstring;
String[] firststring= new String[1000]; //Don't know how to stablish a //dynamic string[] length, letting the user stablish the string[].length
for(int c=0;c<firststring.length;c++){
firststring[c]=word.next();
if(firststring[c].equals(keyword)){
finalstring=firststring[c].substring(0,c);
c=cadena.length-1; //To jump out of the for.
}
}
for (int c=0;c<finalstring.length();c++) {
for(int i=c+1;i<finalstring.length();i++) {
if (firststring[c].compareTo(firststring[i])>0) {
String change = firststring[c];
firststring[c] = firststring[i];
firststring[i] = change;
}
}
}
System.out.print("\nYou entered "end" and the last word classified is "+finalstring[finalstring.length()-1]); //Of course, error here, just did it to put one System.out.print of how should the result be.
}
}
This is what I tried, though, without any type of success, any help of yours will be a big help, thank you ALL!
Don't know how to stablish a dynamic string[] length, letting the user establish the string[].length
It is not necessary to do that. But here's how.
Approach #1: ask the user to give you a number and then allocate the array like this:
String[] strings = new String[theNumber];
Warning: the requirements don't say you are allowed to do that, and you may lose marks for deviating from the requirements.
Approach #2: use an ArrayList to accumulate a list of words, the use List.toArray to create an array from the list contents. (Read the javadocs for list to work it out.)
Of course, error here, just did it to put one System.out.print of how should the result be.
Yea. One problem is that the length is 1000, but you don't have 1000 actual strings in the array. The same problem affects your earlier code too. Think about is ...
I'm not going to fix your code to make it work. I've given you enough hints for you to do that for yourself. If you are prepared to put in the effort.
One more hint: you can / should use break to break out of the first loop.
I know some words are not in English but in Catalan, but the code can be perfectly understood, yesterday I finally programmed this answer:
public static void main(String[] args) {
Scanner entrada= new Scanner(System.in);
System.out.println("Escriu les paraules que vulguis, per acabar, usa la paraula 'fi'.");
String paraules = "";
int c=0;
do {
String paraula = entrada.next();
if (paraula.equals("fi")) {
c++;
} else {
if (paraula.compareTo(paraules) > 0) {
paraules = paraula;
}
}
} while (c==0);
System.out.println("L'última parala ordenada alfabèticament és "+paraules+".\n");
}
}

How to find the word with the most uppercase letters in an ArrayList

I have to enter cities in an array list and then analyze the inputted citites to find the city with the most upercase letters. But i cannot figure out the code to anylyze the enteries in the arraylist and find the word with the most uppercase letters.
package cirties2;
import java.util.Scanner;
import java.util.*;
public class Cirties2 {
public static void main(String[] args)
{
Scanner city = new Scanner(System.in);
System.out.println("Enter the cities<enter stop to exit>");
List<String> cities = new ArrayList<String>( );
boolean thing = true;
while(thing)
{
String s = city.nextLine( );
if(s.equalsIgnoreCase("stop"))
{
System.out.println(cities);
break;
}
else
{
System.out.println("Enter the cities<enter stop to exit>");
cities.add(s);
}
}
}
}
It is too easy, I will give you a few hints though .
Looping through an Array List use the first way
To check whether a letter is Uppercase or not see this
You only care about the word with most Uppercase letters, so keep updating a variable (let's call it track)containing the index of the word with the highest number of uppercase letter whenever you find a word with more uppercase letter than the one track is pointing to.
You shouldn't ask such simple questions here, at least not without trying something first and showing us what you did so far. You will get a lot of down votes. I'm a fairly good programmer now but I'm talking from experience, feels good to be on the patronizing side lol.
Assuming that your strings contain only alphabets, upper case alphabets ASCII values are less than their lower case alternatives. So if u're using String.hashCode(), the string which is having more Upper case alphabets will have the smallest hashcode among all the strings.
Scan through your list, get the hashcode of each string in every iteration, update the minimum if its less than the previous value.
Hope this helps :)

Categories

Resources