Java spell checker using hash tables - java

I don't want any codes. I really want to learn the logic myself but I need pointing to the right direction. Pseudocode is fine. I basically need to create a spell checker using hash tables as my primary data structure. I know it may not be the best data structure for the job but that it what i was tasked to do. The words with correct spellings will come from a text file. Please guide me on how to approach the problem.
The way I'm thinking of doing it:
I'm guessing I need to create a ADT class that takes the string words.
I need a main class that reads the dictionary text file and takes a sentence inputted by a user. This class then scans that string of words then places each word into an ArrayList by noting the spaces in between the words. A boolean method will then pass each word in the Arraylist to the class that will handle misspellings and return if the word is valid or false.
I believe I need to create a class that generates the misspellings from the word list and stores them into the hash table? There will be a boolean method that takes a string parameter that checks in the table if the word is valid and return true or false.
In generating the misspellings, the key concepts I will have to look out for will be:
(Take for example the word: "Hello")
Missing characters. E.g. "Ello", "Helo"
Jumbled version of the word. E.g. "ehllo", "helol"
Phonetic misspelling. E.g. "fello" ('f' for 'h')
How can I improve on this thinking?
EDIT! This is what I came up with using HashSet
/**
* The main program that loads the correct dictionary spellings
* and takes input to be analyzed from user.
* #author Catherine Austria
*/
public class SpellChecker {
private static String stringInput; // input to check;
private static String[] checkThis; // the stringInput turned array of words to check.
public static HashSet dictionary; // the dictionary used
/**
* Main method.
* #param args Argh!
*/
public static void main(String[] args) {
setup();
}//end of main
/**
* This method loads the dictionary and initiates the checks for errors in a scanned input.
*/
public static void setup(){
int tableSIZE=59000;
dictionary = new HashSet(tableSIZE);
try {
//System.out.print(System.getProperty("user.dir"));//just to find user's working directory;
// I combined FileReader into the BufferReader statement
//the file is located in edu.frostburg.cosc310
BufferedReader bufferedReader = new BufferedReader(new FileReader("./dictionary.txt"));
String line = null; // notes one line at a time
while((line = bufferedReader.readLine()) != null) {
dictionary.add(line);//add dictinary word in
}
prompt();
bufferedReader.close(); //close file
}
catch(FileNotFoundException ex) {
ex.printStackTrace();//print error
}
catch(IOException ex) {
ex.printStackTrace();//print error
}
}//end of setUp
/**
* Just a prompt for auto generated tests or manual input test.
*/
public static void prompt(){
System.out.println("Type a number from below: ");
System.out.println("1. Auto Generate Test\t2.Manual Input\t3.Exit");
Scanner theLine = new Scanner(System.in);
int choice = theLine.nextInt(); // for manual input
if(choice==1) autoTest();
else if(choice==2) startwInput();
else if (choice==3) System.exit(0);
else System.out.println("Invalid Input. Exiting.");
}
/**
* Manual input of sentence or words.
*/
public static void startwInput(){
//printDictionary(bufferedReader); // print dictionary
System.out.println("Spell Checker by C. Austria\nPlease enter text to check: ");
Scanner theLine = new Scanner(System.in);
stringInput = theLine.nextLine(); // for manual input
System.out.print("\nYou have entered this text: "+stringInput+"\nInitiating Check...");
/*------------------------------------------------------------------------------------------------------------*/
//final long startTime = System.currentTimeMillis(); //speed test
WordFinder grammarNazi = new WordFinder(); //instance of MisSpell
splitString(removePunctuation(stringInput));//turn String line to String[]
grammarNazi.initialCheck(checkThis);
//final long endTime = System.currentTimeMillis();
//System.out.println("Total execution time: " + (endTime - startTime) );
}//end of startwInput
/**
* Generates a testing case.
*/
public static void autoTest(){
System.out.println("Spell Checker by C. Austria\nThis sentence is being tested:\nThe dog foud my hom. And m ct hisse xdgfchv!## ");
WordFinder grammarNazi = new WordFinder(); //instance of MisSpell
splitString(removePunctuation("The dog foud my hom. And m ct hisse xdgfchv!## "));//turn String line to String[]
grammarNazi.initialCheck(checkThis);
}//end of autoTest
/**
* This method prints the entire dictionary.
* Was used in testing.
* #param bufferedReader the dictionary file
*/
public static void printDictionary(BufferedReader bufferedReader){
String line = null; // notes one line at a time
try{
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
}catch(FileNotFoundException ex) {
ex.printStackTrace();//print error
}
catch(IOException ex) {
ex.printStackTrace();//print error
}
}//end of printDictionary
/**
* This methods splits the passed String and puts them into a String[]
* #param sentence The sentence that needs editing.
*/
public static void splitString(String sentence){
// split the sentence in between " " aka spaces
checkThis = sentence.split(" ");
}//end of splitString
/**
* This method removes the punctuation and capitalization from a string.
* #param sentence The sentence that needs editing.
* #return the edited sentence.
*/
public static String removePunctuation(String sentence){
String newSentence; // the new sentence
//remove evil punctuation and convert the whole line to lowercase
newSentence = sentence.toLowerCase().replaceAll("[^a-zA-Z\\s]", "").replaceAll("\\s+", " ");
return newSentence;
}//end of removePunctuation
}
This class checks for misspellings
public class WordFinder extends SpellChecker{
private int wordsLength;//length of String[] to check
private List<String> wrongWords = new ArrayList<String>();//stores incorrect words
/**
* This methods checks the String[] for spelling errors.
* Hashes each index in the String[] to see if it is in the dictionary HashSet
* #param words String list of misspelled words to check
*/
public void initialCheck(String[] words){
wordsLength=words.length;
System.out.println();
for(int i=0;i<wordsLength;i++){
//System.out.println("What I'm checking: "+words[i]); //test only
if(!dictionary.contains(words[i])) wrongWords.add(words[i]);
} //end for
//manualWordLookup(); //for testing dictionary only
if (!wrongWords.isEmpty()) {
System.out.println("Mistakes have been made!");
printIncorrect();
} //end if
if (wrongWords.isEmpty()) {
System.out.println("\n\nMove along. End of Program.");
} //end if
}//end of initialCheck
/**
* This method that prints the incorrect words in a String[] being checked and generates suggestions.
*/
public void printIncorrect(){//delete this guy
System.out.print("These words [ ");
for (String wrongWord : wrongWords) {
System.out.print(wrongWord + " ");
}//end of for
System.out.println("]seems incorrect.\n");
suggest();
}//end of printIncorrect
/**
* This method gives suggestions to the user based on the wrong words she/he misspelled.
*/
public void suggest(){
MisSpell test = new MisSpell();
while(!wrongWords.isEmpty()&&test.possibilities.size()<=5){
String wordCheck=wrongWords.remove(0);
test.generateMispellings(wordCheck);
//if the possibilities size is greater than 0 then print suggestions
if(test.possibilities.size()>=0) test.print(test.possibilities);
}//end of while
}//end of suggest
/*ENTERING TEST ZONE*/
/**
* This allows a tester to look thorough the dictionary for words if they are valid; and for testing only.
*/
public void manualWordLookup(){
System.out.print("Enter 'ext' to exit.\n\n");
Scanner line = new Scanner(System.in);
String look=line.nextLine();
do{
if(dictionary.contains(look)) System.out.print(look+" is valid\n");
else System.out.print(look+" is invalid\n");
look=line.nextLine();
}while (!look.equals("ext"));
}//end of manualWordLookup
}
/**
* This is the main class responsible for generating misspellings.
* #author Catherine Austria
*/
public class MisSpell extends SpellChecker{
public List<String> possibilities = new ArrayList<String>();//stores possible suggestions
private List<String> tempHolder = new ArrayList<String>(); //telps for the transposition method
private int Ldistance=0; // the distance related to the two words
private String wrongWord;// the original wrong word.
/**
* Execute methods that make misspellings.
* #param wordCheck the word being checked.
*/
public void generateMispellings(String wordCheck){
wrongWord=wordCheck;
try{
concatFL(wordCheck);
concatLL(wordCheck);
replaceFL(wordCheck);
replaceLL(wordCheck);
deleteFL(wordCheck);
deleteLL(wordCheck);
pluralize(wordCheck);
transposition(wordCheck);
}catch(StringIndexOutOfBoundsException e){
System.out.println();
}catch(ArrayIndexOutOfBoundsException e){
System.out.println();
}
}
/**
* This method concats the word behind each of the alphabet letters and checks if it is in the dictionary.
* FL for first letter
* #param word the word being manipulated.
*/
public void concatFL(String word){
char cur; // current character
String tempWord=""; // stores temp made up word
for(int i=97;i<123;i++){
cur=(char)i;//assign ASCII from index i value
tempWord+=cur;
//if the word is in the dictionary then add it to the possibilities list
tempWord=tempWord.concat(word); //add passed String to end of tempWord
checkDict(tempWord); //check to see if in dictionary
tempWord="";//reset temp word to contain nothing
}//end of for
}//end of concatFL
/**
* This concatenates the alphabet letters behind each of the word and checks if it is in the dictionary. LL for last letter.
* #param word the word being manipulated.
*/
public void concatLL(String word){
char cur; // current character
String tempWord=""; // stores temp made up word
for(int i=123;i>97;i--){
cur=(char)i;//assign ASCII from index i value
tempWord=tempWord.concat(word); //add passed String to end of tempWord
tempWord+=cur;
//if the word is in the dictionary then add it to the possibilities list
checkDict(tempWord);
tempWord="";//reset temp word to contain nothing
}//end of for
}//end of concatLL
/**
* This method replaces the first letter (FL) of a word with alphabet letters.
* #param word the word being manipulated.
*/
public void replaceFL(String word){
char cur; // current character
String tempWord=""; // stores temp made up word
for(int i=97;i<123;i++){
cur=(char)i;//assign ASCII from index i value
tempWord=cur+word.substring(1,word.length()); //add the ascii of i ad the substring of the word from index 1 till the word's last index
checkDict(tempWord);
tempWord="";//reset temp word to contain nothing
}//end of for
}//end of replaceFL
/**
* This method replaces the last letter (LL) of a word with alphabet letters
* #param word the word being manipulated.
*/
public void replaceLL(String word){
char cur; // current character
String tempWord=""; // stores temp made up word
for(int i=97;i<123;i++){
cur=(char)i;//assign ASCII from index i value
tempWord=word.substring(0,word.length()-1)+cur; //add the ascii of i ad the substring of the word from index 1 till the word's last index
checkDict(tempWord);
tempWord="";//reset temp word to contain nothing
}//end of for
}//end of replaceLL
/**
* This deletes first letter and sees if it is in dictionary
* #param word the word being manipulated.
*/
public void deleteFL(String word){
String tempWord=word.substring(1,word.length()-1); // stores temp made up word
checkDict(tempWord);
//print(possibilities);
}//end of deleteFL
/**
* This deletes last letter and sees if it is in dictionary
* #param word the word being manipulated.
*/
public void deleteLL(String word){
String tempWord=word.substring(0,word.length()-1); // stores temp made up word
checkDict(tempWord);
//print(possibilities);
}//end of deleteLL
/**
* This method pluralizes a word input
* #param word the word being manipulated.
*/
public void pluralize(String word){
String tempWord=word+"s";
checkDict(tempWord);
}//end of pluralize
/**
* It's purpose is to check a word if it is in the dictionary.
* If it is, then add it to the possibilities list.
* #param word the word being checked.
*/
public void checkDict(String word){
if(dictionary.contains(word)){//check to see if tempWord is in dictionary
//if the tempWord IS in the dictionary, then check if it is in the possibilities list
//then if tempWord IS NOT in the list, then add tempWord to list
if(!possibilities.contains(word)) possibilities.add(word);
}
}//end of checkDict
/**
* This method transposes letters of a word into different places.
* Not the best implementation. This guy was my last minute addition.
* #param word the word being manipulated.
*/
public void transposition(String word){
wrongWord=word;
int wordLen=word.length();
String[] mixer = new String[wordLen]; //String[] length of the passed word
//make word into String[]
for(int i=0;i<wordLen;i++){
mixer [i]=word.substring(i,i+1);
}
shift(mixer);
}//end of transposition
/**
* This method takes a string[] list then shifts the value in between
* the elements in the list and checks if in dictionary, adds if so.
* I agree that this is probably the brute force implementation.
* #param mixer the String array being shifted around.
*/
public void shift(String[] mixer){
System.out.println();
String wordValue="";
for(int i=0;i<=tempHolder.size();i++){
resetHelper(tempHolder);//reset the helper
transposeHelper(mixer);//fill tempHolder
String wordFirstValue=tempHolder.remove(i);//remove value at index in tempHolder
for(int j=0;j<tempHolder.size();j++){
int inttemp=0;
String temp;
while(inttemp<j){
temp=tempHolder.remove(inttemp);
tempHolder.add(temp);
wordValue+=wordFirstValue+printWord(tempHolder);
inttemp++;
if(dictionary.contains(wordValue)) if(!possibilities.contains(wordValue)) possibilities.add(wordValue);
wordValue="";
}//end of while
}//end of for
}//end for
}//end of shift
/**
* This method fills a list tempHolder with contents from String[]
* #param wordMix the String array being shifted around.
*/
public void transposeHelper(String[] wordMix){
for(int i=0;i<wordMix.length;i++){
tempHolder.add(wordMix[i]);
}
}//end of transposeHelper
/**
* This resets a list
* #param thisList removes the content of a list
*/
public void resetHelper(List<String> thisList){
while(!thisList.isEmpty()) thisList.remove(0); //while list is not empty, remove first value
}//end of resetHelper
/**
* This method prints out a list
* #param listPrint the list to print out.
*/
public void print(List<String> listPrint){
if (possibilities.isEmpty()) {
System.out.print("Can't seem to find any related words for "+wrongWord);
return;
}
System.out.println("Maybe you meant these for "+wrongWord+": ");
System.out.printf("%s", listPrint);
resetHelper(possibilities);
}//end of print
/**
* This returns a String word version of a list
* #param listPrint the list to make into a word.
* #return the generated word version of a list.
*/
public String printWord(List<String> listPrint){
Object[] suggests = listPrint.toArray();
String theWord="";
for(Object word: suggests){//form listPrint elements into a word
theWord+=word;
}
return theWord;
}//end of printWord
}

Instead of generating all possible misspellings of the words in your dictionary and adding them to the hash table, consider performing all possible changes (that you already suggested) to the user-entered words, and checking to see if those words are in the dictionary file.

It sounds like what you want is a quick way to verify that a word is spelled correctly, or to find the correct spelling. If this is what your trying to do you can use a HashMap<String,String> (i.e. a hash table with String keys and String values). Whenever you find a word in your dictionary you enter a key for it with a null value indicating that the word is not to be changed (i.e. a correct spelling). You can then compute and add keys for possible misspellings and give the correct word for the value.
You'd have to devise a way to do this very carefully, because if your dictionary has two similar words "clot" and "colt" computed misspellings of one may replace the correct spelling (or misspellings) of the other. Once your done you can look up a word to see if it is in the dictionary, if it is a misspelling of a dictionary word (and which word), or if it is not found at all.
I believe this is a bad design though, because your table has to be exponentially larger than your (I assume, already quite large) dictionary. And because you spent a lot of time calculating many misspelling for every word in the dictionary (very big overhead if you only check a few lines which may contain a few of these words). Given a only a little liberty I would opt for a HashSet<String> (which is a hash table but without values) filled only with dictionary words. This is allows you to check quickly if a word is in the dictionary or not.
You can dynamically compute other ways to spell words when you encounter ones not in your dictionary. If your doing this for only a line or two it should not be slow at all (certainly faster than computing alternatives for everything in your dictionary). But if you wanted to this for every for a whole file you may want to keep a much smaller HashMap<String,String> separate from your dictionary to store any corrections you find since the author may misspell the word the same way in future. Checking this before computing alternatives keeps you from duplicating your efforts several times over.

Related

Replace java giving 2 strings

Well as you can read, when i use the replace function in my code it prints out:
Hey, I'm.
Hey, (name).
When it should only print out Hey, (name).
And i dont understand why. Here is the code:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package fiestaaburrida;
import java.util.Scanner;
/**
*
* #author xBaco
*/
public class FiestaAburrida {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner teclado = new Scanner(System.in);
int times = teclado.nextInt();
int index = 0;
while (index < times){
String greeting = teclado.next();
String newgreeting = greeting.replace("I'm ","");
System.out.println("Hey, "+newgreeting+".");
}
}
}
Scanner.next() will read your input up to the next delimeter, which by default is a space. Because of this, you are getting two inputs, I'm Joe, rather than the one input I'm Joe.
If you want to take in an entire line at once, you should use Scanner.nextLine(). (Though you should watch out for this quirk which will affect you because of your first nextInt.)
It is because teclado.next(); fetches the next value in the console that is separated by a space. You want to use teclado.nextLine();. Although this is not a complete fix. If you were to follow up with this approach and enter "I'm Jake", than the program would print "Hey, ." followed by "Hey, Jake". This is because you are using teclado.nextInt();, which works, but it will not cause Scanner#nextLine() to read "I'm Jake" immediately. Thus you must also replace nextInt(); with nextLine(); and parse it:
public static void main(String[] args) {
Scanner teclado = new Scanner(System.in);
int times = Integer.parseInt(teclado.nextLine());
int index = 0;
while (index < times){
String greeting = teclado.nextLine();
String newgreeting = greeting.replace("I'm ","");
System.out.println("Hey, " + newgreeting + ".");
}
}
Java's String.replace method find one string and replace the one.
So, I recommend you use String.replaceAll
// ....
while (index < times){
String greeting = teclado.next();
String newgreeting = greeting.replaceAll("I'm ","");
System.out.println("Hey, "+newgreeting+".");
}
// ....

How do I read in a text file as a string and extract just a single character? "0"

How do I go about asking for a string input, then extracting the 0 character?
I was using "fstream.next()" and it would input whatever, not just a string.
I just need a character, which I can later use in a loop where the program only accepts char inputs of T, D, and E.
Then the program reads the double. Then the program calls the instance method with the parameters (char, double). The instance method later does it's thing and saves the inputs. The program later loops back and does it all over again.
Currently I am receiving an error "java.util.InputMismatchException". If you could offer suggestions, I'd greatly appreciate it! If clarification is needed, please let me know. Thank you in advance! :)
Here is my code:
/** holds answer of whether user has more inputs or not */
String answer;
/** holds the results when calling inLetter() */
char letter;
/** holds the results when checking for types/strings in txt file */
String inType = "";
/** holds double results when searching line by line the text file */
double inAmount = 0;
/** holds the results when calling inAmount() */
double amount;
/** initiates infile to null */
File infile = null;
/** count system for how many valid lines were read and used */
int count = 0;
/** calls description method */
description();
/** initiates new Object */
GironEventClass newInput = new GironEventClass();
try{
/** defines new variable linked to .dat file */
infile = new File("GironEvent.dat");
/** calls fstream scanner - for use on file */
Scanner fstream = new Scanner(infile);
/** calls while loop. As long as there is a line, the loop continues */
while(fstream.hasNext())
{
/** inputs first string in line of file to variable inType */
inType = fstream.nextLine();
char a_char = inType.charAt(0);
/** inputs first int in line of file to variable inAmount */
inAmount = fstream.nextDouble();
try{
/** calls instance method with two parameters */
newInput.donations(a_char, inAmount);
/** count ticket increases */
count+=1;
}
catch(IllegalArgumentException a){
/** prints out error if exception is caught*/
System.out.println("Just caught an illegal argument exception. ");
}
}
/** closes stream between program and fiel */
fstream.close();
/** outputs line count, and totals per type */
System.out.println("\n" + count + " number of valid lines were read!\n");
System.out.println("Total Sales: " + newInput.getSale());
System.out.println("Donations: " + newInput.getDonated());
System.out.println("Expenses: " + newInput.getExpenses());
}
catch (FileNotFoundException e){
/** Outputs error if file cannot be opened. */
System.out.println("\nGironEvent.dat could not be opened. ");
}
do{
/** loop asks user if there is more that needs to be added to the totals. N exits loop. */
System.out.print("\nAre there any more items to add that were not in the text file? (Type 'Y' or 'N'): ");
answer = keyboard.next();
if (("Y".equals(answer)) || ("y".equals(answer)))
{
letter = inLetter();
amount = inAmount();
newInput.donations(letter, amount);
}
}while (("Y".equals(answer)) || ("y".equals(answer)));
/** calls instance method to display totals in a fancy manner */
newInput.display();
}
/** inLetter - displays types to user. Asks user to input type. Converts input into uppercase letter.
*
* #return resultTwo - Uppercase form of result. Result is the type the user inputted.
*/
public static char inLetter(){
Scanner keyboard = new Scanner(System.in);
String result;
String resultTwo;
System.out.println("T = Tiket Sales");
System.out.println("D = Donations");
System.out.println("E = Expenses");
System.out.print("Please input an identifier ");
result = keyboard.nextLine();
resultTwo = result.toUpperCase();
return resultTwo;
}
/** inAmount - asks user for amount. Tests that amount isn't a negative number or a zero.
*
* #return result - the amount the user inputed. regardless if it was the first or tenth time.
*/
public static double inAmount(){
Scanner keyboard = new Scanner(System.in);
double result;
System.out.println("Please input an amount ");
result = keyboard.nextDouble();
if(result <= 0){
System.out.print("Please input a positive and non-zero amount ");
result = keyboard.nextDouble();
}
return result;
}
/** description - displays a description of what the program does
* void.
*/
public static void description(){
System.out.println("The program will ask you what amount is being spent on what.");
System.out.println(" ex: expenses, ticket sales, and profts.");
System.out.println("This program will help determine whether the event generated or lost money.");
}
I need assistance with the following block:
/** inputs first string in line of file to variable inType */
inType = fstream.nextLine();
char a_char = inType.charAt(0);
/** inputs first int in line of file to variable inAmount */
inAmount = fstream.nextDouble();
Your fstream is having a combination of String and Double.
So when you use fstream.nextDouble() it throws java.util.InputMismatchException
Reference: http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextDouble()
You can first check whether the next character is double or not with the method hasNextDouble()
Reference:
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#hasNextDouble()

ArrayList: Get length of longest string, Get average length of string

In Java, I have a method that reads in a text file that has all the words in the dictionary, each on their own line.
It reads each line by using a for loop and adds each word to an ArrayList.
I want to get the length of the longest word (String) in the Array. In addition, I want to get the length of the longest word in the dictionary file. It would probably be easier to split this into several methods, but I don't know the syntax.
So far, the code is have is:
public class spellCheck {
static ArrayList <String> dictionary; //the dictonary file
/**
* load file
* #param fileName the file containing the dictionary
* #throws FileNotFoundException
*/
public static void loadDictionary(String fileName) throws FileNotFoundException {
Scanner in = new Scanner(new File(fileName));
while (in.hasNext())
{
for(int i = 0; i < fileName.length(); ++i)
{
String dictionaryword = in.nextLine();
dictionary.add(dictionaryword);
}
}
Assuming that each word is on it's own line, you should be reading the file more like...
try (Scanner in = new Scanner(new File(fileName))) {
while (in.hasNextLine()) {
String dictionaryword = in.nextLine();
dictionary.add(dictionaryword);
}
}
Remember, if you open a resource, you are responsible for closing. See The try-with-resources Statement for more details...
Calculating the metrics can be done after reading the file, but since your here, you could do something like...
int totalWordLength = 0;
String longest = "";
while (in.hasNextLine()) {
String dictionaryword = in.nextLine();
totalWordLength += dictionaryword.length();
dictionary.add(dictionaryword);
if (dictionaryword.length() > longest.length()) {
longest = dictionaryword;
}
}
int averageLength = Math.round(totalWordLength / (float)dictionary.size());
But you could just as easily loop through the dictionary and use the same idea
(nb- I've used local variables, so you will either want to make them class fields or return them wrapped in some kind of "metrics" class - your choice)
Set a two counters and a variable that holds the current longest word found before you start reading in with your while loop. To find the average have one counter be incremented by one each time the line is read and have the second counter add up the total number of characters in each word (obviously the total number of characters entered, divided by the total number of words read -- as denoted by the total number of lines -- is the average length of each word.
As for the longest word, set the longest word to be the empty string or some dummy value like a single character. Each time you read in a line compare the current word with the previously found longest word (using the .length() method on the String to find its length) and if its longer set a new longest word found
Also, if you have all this in a file, I'd use a buffered reader to read in your input data
May be this could help
String words = "Rookie never dissappoints, dont trust any Rookie";
// read your file to string if you get string while reading then you can use below code to do that.
String ss[] = words.split(" ");
List<String> list = Arrays.asList(ss);
Map<Integer,String> set = new Hashtable<Integer,String>();
int i =0;
for(String str : list)
{
set.put(str.length(), str);
System.out.println(list.get(i));
i++;
}
Set<Integer> keys = set.keySet();
System.out.println(keys);
System.out.println(set);
Object j[]= keys.toArray();
Arrays.sort(j);
Object max = j[j.length-1];
set.get(max);
System.out.println("Tha longest word is "+set.get(max));
System.out.println("Length is "+max);

How do I ignore case when using startsWith and endsWith in Java? [duplicate]

This question already has answers here:
How to use `string.startsWith()` method ignoring the case?
(8 answers)
Closed 5 years ago.
Here's my code:
public static void rightSel(Scanner scanner,char t)
{
/*if (!stopping)*/System.out.print(": ");
if (scanner.hasNextLine())
{
String orInput = scanner.nextLine;
if (orInput.equalsIgnoreCase("help")
{
System.out.println("The following commands are available:");
System.out.println(" 'help' : displays this menu");
System.out.println(" 'stop' : stops the program");
System.out.println(" 'topleft' : makes right triangle alligned left and to the top");
System.out.println(" 'topright' : makes right triangle alligned right and to the top");
System.out.println(" 'botright' : makes right triangle alligned right and to the bottom");
System.out.println(" 'botleft' : makes right triangle alligned left and to the bottom");
System.out.println("To continue, enter one of the above commands.");
}//help menu
else if (orInput.equalsIgnoreCase("stop")
{
System.out.println("Stopping the program...");
stopping = true;
}//stop command
else
{
String rawInput = orInput;
String cutInput = rawInput.trim();
if (
I'd like to allow the user some leeway as to how they can enter the commands, things like: Top Right, top-right, TOPRIGHT, upper left, etc.
To that end, I'm trying to, at that last if (, check if cutInput starts with either "top" or "up" AND check if cutInput ends with either "left" or "right", all while being case-insensitive. Is this at all possible?
The end goal of this is to allow the user to, in one line of input, pick from one of four orientations of a triangle. This was the best way I could think of to do that, but I'm still quite new to programming in general and might be over complicating things. If I am, and it turns there's a simpler way, please let me know.
Like this:
aString.toUpperCase().startsWith("SOMETHING");
aString.toUpperCase().endsWith("SOMETHING");
The accepted answer is wrong. If you look at the implementation of String.equalsIgnoreCase() you will discover that you need to compare both lowercase and uppercase versions of the Strings before you can conclusively return false.
Here is my own version, based on http://www.java2s.com/Code/Java/Data-Type/CaseinsensitivecheckifaStringstartswithaspecifiedprefix.htm:
/**
* String helper functions.
*
* #author Gili Tzabari
*/
public final class Strings
{
/**
* #param str a String
* #param prefix a prefix
* #return true if {#code start} starts with {#code prefix}, disregarding case sensitivity
*/
public static boolean startsWithIgnoreCase(String str, String prefix)
{
return str.regionMatches(true, 0, prefix, 0, prefix.length());
}
public static boolean endsWithIgnoreCase(String str, String suffix)
{
int suffixLength = suffix.length();
return str.regionMatches(true, str.length() - suffixLength, suffix, 0, suffixLength);
}
/**
* Prevent construction.
*/
private Strings()
{
}
}
I was doing an exercise in my book and the exercise said, "Make a method that tests to see if the end of a string ends with 'ger.' Write the code to where it tests for any combination of upper-case and lower-case letters in the phrase 'ger.'"
So, basically, it asked me to test for a phrase within a string and ignore the case so it doesn't matter if letters in "ger" are upper or lower-case. Here is my solution:
package exercises;
import javax.swing.JOptionPane;
public class exercises
{
public static void main(String[] args)
{
String input, message = "enter a string. It will"
+ " be tested to see if it "
+ "ends with 'ger' at the end.";
input = JOptionPane.showInputDialog(message);
boolean yesNo = ends(input);
if(yesNo)
JOptionPane.showMessageDialog(null, "yes, \"ger\" is there");
else
JOptionPane.showMessageDialog(null, "\"ger\" is not there");
}
public static boolean ends(String str)
{
String input = str.toLowerCase();
if(input.endsWith("ger"))
return true;
else
return false;
}
}
as you can see from the code, I simply converted the string that a user would input to all lower-case. It would not matter if every letter was alternating between lower and upper-case because I negated that.

Java algorithm palindrome&

/**
* #(#)palindrome1.java
*
* palindrome1 application
*
* #author
* #version 1.00 2013/11/15
*/
public class palindrome1 {
static boolean isPalindrome(String str) {
int count=0;
//check all characters of sequence is palindrome
for(int i = 0; i < str.length();i++)
{
if(str.charAt(i)!=str.charAt(str.length()-1-i))
{
return false;
}
}
//if it is return true otherwise return false
return true;
}
public static void main(String[] args) {
// TODO, add your application code
String sentence= "bob gave that pop race car to me." ;
String sentenceMax="";
String sentenceNew="";
sentence = sentence.replace( " ","");
for(int i = 0;i<sentence.length();i++)
{
for(int k=0;k<i;k++)
{
sentenceNew = sentence.substring(k,i);
if(isPalindrome(sentenceNew)&&sentenceNew.length()>sentenceMax.length());
{
sentenceMax=sentenceNew;
sentenceNew="";
}
}
}
System.out.println(sentenceMax);
}
}
The question is:t should ask a sentence from user and find the longest palindrome substring in the sentence ignoring the spaces in the sentence and print the longest palindrome substring. You MUST use the function you wrote in Part B. The sentences must be case-insensitive.
and part B is the first method named isPalindrome() in mycode.
The output should be:
racecar
but my code outputs:
e
What is wrong at my code?
You have in your code :
if(isPalindrome(sentenceNew)&&sentenceNew.length()>sentenceMax.length());
And ; is at the bad place. Since it is there it treats it as a if with an empty block, so your real block {} is calculated all the time.
It should be:
if(isPalindrome(sentenceNew)&&sentenceNew.length()>sentenceMax.length())
You are assigning a new value to sentenceMax each iteration. Try this instead
sentenceMax += sentenceNew;
Why did you not use the StringBuffer methods ?
StringBuffer.reverse() can reverse the String
after that you can search each substring in the reverted Source string using StringBuffer.indexOf(subString).
Isnt that a much simpler approach ?

Categories

Resources