我得到的錯誤:我應該如何解決Java中的這個「非法表達式」錯誤?
Error: (65, 3) java: illegal start of expression
參照這一行:
public boolean equals(WordList wordList)
我認爲這是由一些與字符串數組WordList[]
的範圍所致。但是,似乎這應該是可以接受的,因爲我在構造函數中調用了一個變量的實例。
我曾嘗試將WordList[]
構造更改爲public equals(WordList wordList)
,boolean equals(WordList wordList)
和其他組合,但這些組合都沒有更改錯誤消息。
代碼:
public class WordList
{
String[] words;
public int count;
//constructor
public WordList()
{
//create a size two array of strings and assign it to words instance variable
words = new String[2];
count = 0;
}
public int addWord(String word)
{
if(findWord(word) == -1) //word not in list
{
return count;
}
if(words.length == count)
{
String[] temp = new String[words.length * 2];
for(int n = 0; n < words.length; n++)
{
temp[i] = words[i];
}
words = temp;
}
words[count] = word;
count++;
return count;
}
public void removeWord(String word) //void bc returns nothing
{
int index = findWord(word); // to minimize how many times we call method
if(index == -1)
{
return;
}
for(int n = index; n < count -1; n++)
{
words[n] = words[n + 1];
}
words[count - 1] = "";
count --;
return;
}
public int findWord(String word) {
//iterate over each word in current list
//return index of word if found
for (int i = 0; i < count; i++)
{
if (words[i].equals(word))
{
return i;
}
return -1;
}
public boolean equals(WordList wordList)
{
boolean boolEquals;
//override equals method in Object class
//first checks if number of words in each WordList is equal
//if true -> iterate through all words in 1 of lists +
if(count == wordlist.count)
{
for(int i = 0; i < count; i++)
{
if(findWord(words[i]) == -1)
{
boolEquals = false;
}
boolEquals = true;
}
}
boolEquals = false;
return boolEquals;
}
public String toString()
{
//provide number of words in a string and then list each word on a new line
String result = "";
result += "There are " + count + " words in the word list: \n";
for(int i = 0; i < count; i++)
{
result += words[i] + "\n";
}
return result;
}
public static void main(String[] args)
{
}
是什麼原因造成這個問題?我寧願保留構造函數,儘可能少地修改代碼,以使其成爲一種學習體驗,而不是簡單地從其他人處獲取代碼。
這將更容易解決與適當的選項卡。 – Compass
如果你的代碼被明智地縮進了,那麼很容易就能看出問題出在哪裏。 – khelwood
@Compass我應該怎麼做標籤? –