【问题标题】:How should I fix this "illegal start of expression" error in Java?我应该如何在 Java 中修复这个“非法的表达式开始”错误?
【发布时间】:2017-04-12 09:34:27
【问题描述】:

我收到错误:

错误:(65, 3) java: 表达式的非法开始

参考这一行:

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)
{
}

是什么导致了这个错误信息?我宁愿保留构造函数并尽可能少地对代码进行更改以使其成为一种学习体验,而不是简单地从其他人那里获取代码。

【问题讨论】:

标签: java arrays boolean boolean-logic


【解决方案1】:

语法错误 - 方法中缺少 }

public int findWord(String word) {

【讨论】:

    【解决方案2】:

    您的代码在第 62 行缺少“}”...

    您也应该在第 26 行将 'i' 替换为 'n'...

    【讨论】:

    • 谢谢,这些建议已经解决了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-25
    • 1970-01-01
    • 1970-01-01
    • 2015-05-30
    • 2014-03-09
    • 1970-01-01
    相关资源
    最近更新 更多