Мне было интересно, может ли кто-нибудь помочь с ошибкой, с которой я сталкиваюсь в проекте, над которым я работаю. В настоящее время я работаю над программой Concordance, которая принимает слова и вставляет их в массив. Если слово уже есть, оно добавит 1 к счетчику слова. В конце он покажет, сколько раз слово вводилось в программу.Согласие Java-программа не печатала правильный вывод
В коде ниже у меня есть 3 класса:
1-й класс создает объект с 2-х переменной строкой и Int и пару методов.
public class Concordance
{
private String word;//Stores a word
private int counter = 0;//Stores how many times a word comes up.
/**
* Constructor:
*
* Gives a default value to word if nothing is put in.
*/
public Concordance()
{
word = "";
}
/**
* Constructor
*
* Takes users input and sets it equal to word.
* Adds 1 to counter
*
* @param String input
*/
public Concordance(String input)
{
word = input;
counter = 1;
}
/**
* Adds a 1 to a word's counter
*/
public void addCounter()
{
this.counter++;
}
/**
* Returns the string of the object.
*
* @return word
*/
public String getString()
{
return word;
}
/**
* Returns the number of times the word was put in.
*
* @return counter
*/
public int getCount(){
return counter;
}
}
Второй класс, который является один У меня возникли проблемы с, создает массив объектов в 1-ом классе и некоторые методы, которые будут проверять, если слово уже в массиве. Если это так, он добавит 1 к счетчику слова, иначе он добавит слово в конец массива. Метод insertWord() дает мне странный вывод. Условный оператор внутри цикла for не работает должным образом. Когда я вставляю несколько слов, он будет распознавать только одно слово несколько раз, но каждое слово после этого просто помещается в конец массива, когда ему нужно просто добавить счетчик.
Этот класс также имеет способ печати массива и конструктора.
public HashTable()
{
Concordance temp = new Concordance();
for(int i = 0; i < 255; i++)
{
arrayWords[i] = temp;
}
arrayCounter = 0;
}
/**
* insertWord()
*
* Checks if the word is already in the array.
* If it is in the Array it will add 1 to the counter,
* if not it will add it to the end of the array.
*
* @param String word
*/
public void insertWord(String word)
{
for(int i = 0; i < arrayWords.length; i++)
{
System.out.println(i);
/*Checks if the word is already in the array.
*If it is,it will add 1 to the counter of the word
* or else it will add the word to the end of the array.
*/
if(word.toLowerCase() == arrayWords[i].getString())
{
System.out.println("Adding to Counter to word " + word);
arrayWords[i].addCounter();//Adds 1 to the counter of the word.
break;
}
else
{
System.out.println("Adding " + word +" to Array");
Concordance temp = new Concordance(word);
//Adds the word at the end of the array
arrayWords[arrayCounter] = temp;
arrayCounter++;//Updates the counter array.
break;
}//End of Conditional statement.
}//End of for loop
}//End of insertWord method
/**
* printWords() method
*
* It prints every Concordance object with their string and counter.
*/
public void printWords()
{
System.out.print("\nprinting words\n");
for(int i = 0; i < arrayCounter; i++)
{
System.out.println("The Word " + arrayWords[i].getString() + " comes up in the text " + arrayWords[i].getCount() + " times");
}
}
}//End of Hash Table Class.
3-й класс - это только основной класс, который я тестировал выход, вставляющий несколько слов в таблицу хешей.
public class Main {
public static void main(String [] arg)
{
//Instantiates a Concordance object.
Concordance c = new Concordance("hello");
//Prints the string of the object.
System.out.print(c.getString());
//Prints the counter of the object.
System.out.println(c.getCount());
//Instantiates a hash table
HashTable ht = new HashTable();
//Inserts different values to the Hash Table
ht.insertWord("hello");
ht.insertWord("hello");
ht.insertWord("there");
ht.insertWord("how");
ht.insertWord("hello");
ht.insertWord("are");
ht.insertWord("you");
ht.insertWord("there");
ht.printWords();
}//end of static void
Вот что выглядит результат:
«вводное слово появляется в тексте 4 раза
Слово ИДК приходит в тексте 1 раз
Слово adcadc появляется в тексте 1 раз
Слово idk появляется в тексте 1 раз
Слово ИДК приходит в тексте 1 раз»
Я также использовал учебники указывают, чтобы проверить мой код: http://www.tutorialspoint.com/compile_java_online.php?PID=0Bw_CjBb95KQMRkZzalMwb2pLOWMThis is an online compiler where you can test the code
Спасибо вам большое за взглянуть на это я играл с ним но я не могу заставить его работать. Если у вас есть какие-либо комментарии о моем стиле кодирования или о том, что я должен смотреть, это очень ценится.