Is there a way for my spellchecker to properly work - java

The problem is my spellchecker, that I am trying to make. I have a dictionary file that contains large amount of words to compare with the user input so it can detect any possible spelling errors. The problem with mine, is that regardless of what you type it will always say that the spelling is incorrect when it is not. Is there any solution or a better method to detect selling errors of the user input.
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class SpellChecker2 {
public static void main(String[] args) throws FileNotFoundException
{
Scanner input = new Scanner(System.in);
System.out.println("Please enter a String");
String userWord = input.nextLine();
final String theDictionary = "dictionary.txt";
String[] words = dictionary(theDictionary);
boolean correctSpelling = checking(words, userWord);
if (!correctSpelling)
{
System.out.println("Incorrect spelling");
}
else
{
System.out.println("The spelling is correct");
}
}
public static String[] dictionary(String filename) throws FileNotFoundException
{
final String fileName = "dictionary.txt";
Scanner dictionary = new Scanner(new File(fileName));
int dictionaryLength =0;
while (dictionary.hasNext())
{
++dictionaryLength;
dictionary.nextLine();
}
String [] theWords = new String[dictionaryLength];
for ( int x = 0; x < theWords.length ; x++)
dictionary.close();
return theWords;
}
public static boolean checking(String[] dictionary, String userWord)
{
boolean correctSpelling = false;
for ( int i =0; i < dictionary.length; i++)
{
if (userWord.equals(dictionary[i]))
{
correctSpelling = true;
}
else
correctSpelling = false;
}
return correctSpelling;
}
}
The result I get is:
Please enter a String
hello
Incorrect spelling
As you can see the, even though my spelling was correct, it gives an error that the spelling was incorrect. Any help would be great and thank you in advance.

Yes. Return from checking on true. As you have it now, it can only be true if the last word matches. Like,
public static boolean checking(String[] dictionary, String userWord) {
for ( int i =0; i < dictionary.length; i++) {
if (userWord.equals(dictionary[i])) {
return true;
}
}
return false;
}
Also, you need to populate your dictionary by adding words to your array.
And, I would prefer try-with-resources over explicit close() calls. Something like,
public static String[] dictionary(String filename) throws FileNotFoundException {
final String fileName = "dictionary.txt";
int dictionaryLength = 0, i = 0;
try (Scanner dictionary = new Scanner(new File(fileName))) {
while (dictionary.hasNextLine()) {
++dictionaryLength;
dictionary.nextLine();
}
}
String[] theWords = new String[dictionaryLength];
try (Scanner dictionary = new Scanner(new File(fileName))) {
while (dictionary.hasNextLine()) {
theWords[i] = dictionary.nextLine();
i++;
}
}
return theWords;
}

Related

The occurrence of a substring in a text with many lines

I wrote a program that counts the total number of occurrences of some substring in a string
But there can be many lines in the text
Now there are 3 lines in the text, and the program outputs a value for each of the lines
The code outputs 3 numbers, although I need one, which is how to fix it? another cycle?
public class OccurrencesAmount {
public static int getOccurrencesAmount(String substring, String string) {
substring = substring.toUpperCase();
string = string.toUpperCase();
int count = 0;
int fromIndex = 0;
int length = substring.length();
while (true) {
int occurrenceIndex = string.indexOf(substring, fromIndex);
if (occurrenceIndex < 0) {
break;
}
count++;
fromIndex = occurrenceIndex + length;
}
return count;
}
public static void main(String[] args) throws FileNotFoundException {
try (Scanner scanner = new Scanner(new FileInputStream("input.txt"))) {
String searchLine = "о";
while (scanner.hasNextLine()) {
System.out.println(
getOccurrencesAmount(searchLine, scanner.nextLine()));
}
}
}
}
At the moment your program outputs for every single line.
Your method is already returning an int-value. So to get the total amount of occurences over all lines, you just need to sum them up like this:
public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
String searchLine = "о";
int totalOccurences = 0;
while (scanner.hasNextLine()) {
totalOccurences += getOccurrencesAmount(searchLine, scanner.nextLine());
}
System.out.println(totalOccurences);
}
}

How to read an empty string to create output

I have file of which I need to read input. On one of the lines, there is no name added. In this case, I want to print out that no match was found. The problem that I'm having is that I don't know how I can make sure the program actually reads the part as an empty string. What happens now is that the will just leave the line empty on the console.
The date input looks like this:
5=20=22=10=2=0=0=1=0=1;Vincent Appel,Johannes Mondriaan
2=30=15=8=4=3=2=0=0=0;
class Administration {
public static final int TOTAL_NUMBER_OF_SIMULARITY_SCORES = 10;
public static final String ZERO_MATCHES = "_";
public static final String LESS_THAN_TWENTY_MATCHES= "-";
public static final String TWENTY_OR_MORE_MATCHES = "^";
PrintStream out;
Administration() {
out = new PrintStream(System.out);
}
void printSimilarityScores (Scanner similarityScoresScanner, String similarityScoresInput) {
similarityScoresScanner.useDelimiter("=|;");
int length = similarityScoresInput.length();
for (int i = 0; i < TOTAL_NUMBER_OF_SIMULARITY_SCORES; i++) {
int grade = similarityScoresScanner.nextInt();
if (grade == 0) {
out.printf(ZERO_MATCHES);
} else if (grade < 20) {
out.printf(LESS_THAN_TWENTY_MATCHES);
} else {
out.printf(TWENTY_OR_MORE_MATCHES);
}
}
System.out.print("\n");
similarityScoresScanner.useDelimiter(";|,");
while(similarityScoresScanner.hasNext()) {
String name = similarityScoresScanner.next();
if (length < 22) {
out.printf("No matches found\n");
} else {
System.out.print("\n" + name);
}
}
}
void start() {
Scanner fileScanner = UIAuxiliaryMethods.askUserForInput().getScanner();
while (fileScanner.hasNext()) {
String finalGradeInput = fileScanner.nextLine();
String similarityScoresInput = fileScanner.nextLine();
Scanner finalGradeInputScanner = new Scanner(finalGradeInput);
Scanner similarityScoresScanner = new Scanner(similarityScoresInput);
printFinalGrade(finalGradeInputScanner);
printSimilarityScores(similarityScoresScanner, similarityScoresInput);
}
}
public static void main(String[] argv) {
new Administration().start();
}
}
An easier solution would be to read the file, line by line and handle them like this :
split by the separator
check if there is more than 1 element,
if positive print them
Scanner similarityScoresScanner = new Scanner(myFile);
while (similarityScoresScanner.hasNextLine()) {
String[] content = similarityScoresScanner.nextLine().split("[;,]");
if (content.length == 1) {
System.out.println("No matches found");
} else {
for (int i = 1; i < content.length; i++) {
System.out.println(content[i]);
}
}
}

Java program not terminating when using scanner with System.in

I am unable to terminate my java program which takes some strings as input, below is the code I used to process the input
import java.util.Scanner;
public class EPALIN {
public static void main(String[]args)
{
Scanner sc = new Scanner(System.in);
String p = null;
while((p=sc.nextLine())!=null)
{
System.out.println(getPalin(p));
}
sc.close();
}
public static String getPalin(String st)
{
int i =0;
int j = st.length()-1;
String res = "";
while(i<=j)
{
if(st.substring(i, i+1).equals(st.substring(j, j+1)))
{
res+=st.substring(i, i+1);
i++;
j--;
}
else
{
res+=st.substring(i,i+1);
i++;
}
}
if(res.length()%2==0)
return res+(new StringBuffer(res).reverse().toString());
else
return res+(new StringBuffer(res).reverse().toString().substring(1));
}
}
Even using
while((p=sc.nextLine())!="")
didn't work, its a problem from SPOJ problemId EPALIN
Do something like this
while(!(p=sc.nextLine()).equals("")) {
// ...
}
I try your code with the while i'm using and it's seems to work.
public static void main(String[]args)
{
Scanner sc = new Scanner(System.in);
String p = null;
while(!(p=sc.nextLine()).equals(""))
{
System.out.println(getPalin(p));
}
sc.close();
}
public static String getPalin(String st)
{
int i=0;
int j=st.length()-1;
String res = "";
while(i<=j)
{
if(st.substring(i, i+1).equals(st.substring(j, j+1)))
{
res+=st.substring(i, i+1);
i++;
j--;
}
else
{
res+=st.substring(i,i+1);
i++;
}
}
if(res.length()%2==0)
return res+(new StringBuffer(res).reverse().toString());
else
return res+(new StringBuffer(res).reverse().toString().substring(1));
}
}
You should use hasNext()
String delimiter = "\r\n|\r"; //Or try System.getProperty("line.separator");
Scanner scanner = new Scanner(System.in);
scanner.useDelimiter(delimiter);
while (scanner.hasNext()) {
String p = scanner.next();
// ...
}
}
See the Scanner documentation. Scanner.nextLine() won't return null. If the input ends (for instance, the judge has piped a file to stdin, and the file ends), it will instead throw NoSuchElementException. If it doesn't, nextLine() will block.
Ordinarily what you could do here, because the the problem description states that each test case will be on its own line is (similar to what CandiedOrange suggested):
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
...
}
However, the problem also states:
Large I/O. Be careful in certain languages.
In contest problem lingo, this means "don't use Scanner." For fast I/O, you have a couple of options, but something like the following should work fine while keeping you under the time limit:
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(
System.in));
String line;
while ((line = in.readLine()) != null)
doSomething(line); // etc
}
Note that you will most likely also have to collect all of your output and print it at the end, rather than making a bunch of System.out.println(), which have overhead that you can avoid by only printing once.

Trouble matching states to capitals

I created two arrays and assigned states to one array and capitals to the other array that I got from a text file. The text file is formatted like this:
Colorado,Denver,
Wisconsin,Madison,
..........etc
My code is as follows:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class StatesAndCapitals {
public static void main(String[] args) throws FileNotFoundException {
FileInputStream is = new FileInputStream("capitals.txt");
Scanner input = new Scanner(is);
String[] states = new String[50];
String[] capitals = new String[50];
for (int i = 0; i < states.length; i++){
String currentLine = input.nextLine();
int a = currentLine.indexOf(",");
String states1 = currentLine.substring(0, a);
states[i] = states1;
int b = currentLine.lastIndexOf(",");
String capitals1 = currentLine.substring(a+1, b);
capitals[i] = capitals1;
}//end for loop
}
}
The point of my program is to ask "What is the capital of (blank)?"
Then I need to tell the person if they are correct or not. The problem I'm having is that I don't know how to check if, for example, Madison is the capital of Wisconsin. Any help would be appreciated.
public static void main(String[] args) {
Scanner userInput = null;
Scanner scanner = null;
try {
userInput = new Scanner(System.in);
scanner = new Scanner(new File("capitals.txt"));
while (scanner.hasNext()) {
String[] stateAndCapital = scanner.next().split(",");
System.out.println(String.format("What is the capital of %s?",
stateAndCapital[0]));
System.out.println(userInput.next().equals(stateAndCapital[1]));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
scanner.close();
userInput.close();
}
}
output:
What is the capital of Colorado?
dunno
false
What is the capital of Wisconsin?
Madison
true
Try using this:
public boolean isCapitalOfState(String capital, String state) {
for (int i = 0; i < state.length; i++) {
if (state[i].equals(state) && capitals[i].equals(capital)) {
return true;
}
}
return false;
}
It loops through the array of states and once it has found the match, it will check if the capital matches, if so return true. If it has not found anything it will by default return false.
Note though that there are a lot of easier ways to achieve your behaviour. Generally, Lists are superior to Arrays.
EDIT: I see your question asks for a bit more, we here cannot give you a full program to do it. However do keep in mind that when you've already obtained an index in state, that you can check the result way easier than this.
These are setup like parallel arrays correct? Meaning for example states[0] = colorado, and capitals[0] = denver, it looks this way but if it is indeed setup like this use the index of the state as the index for the capital and compare the input against that.
For example,
System.out.println("What is the capital of " + states[i]);
capital = input.nextLine();
if(capital.equals(capitals[i]){
return true;
}
else{
return false;
}

Capitalize every word using Scanner(System.in) Java

This code should allow the user to input a sentence, change it to lower case, and then capitalize the first letter of each word. But I can't get the scanner to work, it just prints nothing. Any suggestions?
public class Capitalize
{
public static void capCase(String theString)
{
String source = theString;
StringBuffer res = new StringBuffer();
char[] chars = theString.toLowerCase().toCharArray();
boolean found = false;
for(int i = 0; i<chars.length; i++)
{
if(!found&& Character.isLetter(chars[i])){
chars[i] = Character.toUpperCase(chars[i]);
found = true;
} else if (Character.isWhitespace(chars[i])){
found = true;
}
}
}
public static void main(String[] args)
{
Scanner scanner=new Scanner(System.in);
System.out.println(scanner.next());
}
}
Problems as I see them:
The code as it stands will only print the first word typed in once the user presses enter
The method doesn't return anything, so effectively it does all that work and discards it.
So here is what I might do:
I'm going to put everything in main for the sake of concision
public class Capitalize {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String sentence = Scanner.nextLine();
StringBuilder ans = new StringBuilder(); // result
for(String s : sentence.split(" ")) { // splits the string at spaces and iterates through the words.
char[] str = s.toLowerCase().toCharArray(); // same as in OPs code
if(str.Length>0) // can happen if there are two spaces in a row I believe
str[0]=Character.toUpperCase(str[0]); // make the first character uppercase
ans.Append(str); // add modified word to the result buffer
ans.Append(' '); // add a space
}
System.out.println(ans);
}
}
You forgot to call the capCase() method, your code only asks for input from stdin and prints it out straight
I tried running the program in main method it runs fine for me. But if you want to get the whole sentence you will have to call scanner like an iterator and then get each next token bu calling scanner.next() method Scanner deliminates words in a sentence on the basis of white spaces. my example implementation is as follows. The you can pass each word in the your function to process it.
`public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
while (scanner.hasNext())
System.out.println(scanner.next());
}`
I would probably do this
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) { // While there is input.
String line = scanner.nextLine(); // read a line.
int i = 0;
for (String s : line.split(" ")) { // split on space... word(s).
if (i != 0) {
System.out.print(" "); // add a space, except for the first word on a line.
}
System.out.print(capCase(s)); // capCase the word.
i++; // increment our word count.
}
System.out.println(); // add a line.
System.out.flush(); // flush!
}
}
public static String capCase(String theString) {
if (theString == null) {
return ""; // Better safe.
}
StringBuilder sb = new StringBuilder(theString
.trim().toLowerCase()); // lowercase the string.
if (sb.length() > 0) {
char c = sb.charAt(0);
sb.setCharAt(0, Character.toUpperCase(c)); // uppercase the first character.
}
return sb.toString(); // return the word.
}
Problem :
1.you need to send the complete Line and send the String to the function capCase()
2.You are not returning the char array back to the caller.
Solution
1.use the below statement to read complete Line
String str=scanner.nextLine();
2.Change return type of capCase() from void to char[] as below:
public static char[] capCase(String theString)
you should return the char[] variable chars from capCase() function as below:
return chars;
Complete Code:
public static char[] capCase(String theString)
{
String source = theString;
StringBuffer res = new StringBuffer();
char[] chars = theString.toLowerCase().toCharArray();
boolean found = false;
for(int i = 0; i<chars.length; i++)
{
if(!found&& Character.isLetter(chars[i])){
chars[i] = Character.toUpperCase(chars[i]);
found = true;
} else if (Character.isWhitespace(chars[i])){
found = true;
}
}
return chars;
}
public static void main(String[] args)
{
Scanner scanner=new Scanner(System.in);
String str=scanner.nextLine();
System.out.println(capCase(str));
}
Try,
public static void main(String[] args) {
System.out.println(capCase("hello world"));
}
public static String capCase(String theString) {
StringBuilder res = new StringBuilder();
String[] words=theString.split(" +");
for (String word : words) {
char ch=Character.toUpperCase(word.charAt(0));
word=ch+word.substring(1);
res.append(word).append(" ");
}
return res.toString();
}
Try this code it worked for me:
import java.util.Scanner;
public class Capitalize {
/**
* This code should allow the user to input a sentence, change it to lower
* case, and then capitalize the first letter of each word. But I can't get
* the scanner to work, it just prints nothing. Any suggestions?
*
* #param theString
*/
public static void capCase(String theString) {
String source = theString.trim();
StringBuffer res = new StringBuffer();
String lower = theString.toLowerCase();
String[] split = lower.split(" ");
for (int i = 0; i < split.length; i++) {
String temp = split[i].trim();
if (temp.matches("^[a-zA-Z]+")) {
split[i] = temp.substring(0, 1).toUpperCase()
+ temp.substring(1);
}
res.append(split[i] + " ");
}
System.out.println(res.toString());
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
capCase(scanner.nextLine());
// System.out.println(scanner.next());
}
}
I've tested it. It works.
import java.util.Scanner;
import org.apache.commons.lang3.text.WordUtils;
public class Capitalize {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
while(s.hasNextLine()) {
System.out.println(WordUtils.capitalize(s.nextLine()));
}
}
}

Categories