Unable to add a String to an ArrayList: “misplaced construct(s)”

左心房为你撑大大i 提交于 2019-12-19 10:14:19

问题


I am trying to add a string to an ArrayList in Java, but I can't seem to get it to work.

Currently, I have the following code:

List food_names = new ArrayList();

food_names.add("pizza");

Why do I get these errors:

  • Syntax error on token ""pizza"", delete this token
  • Syntax error on token(s), misplaced construct(s)

回答1:


You have to use food_names.add("pizza") in function, for example:

public void AddFood()
{
  food_names.add("pizza");
}

Hope helps




回答2:


why don't you use List Generics List interface.

 List<String> food_names = new ArrayList<String>();

food_names.add("pizza");

This shouldn't give any error.




回答3:


I suspect that those statements are at the top level of a class. The first one is OK there, but the second one can only be inside a code block; e.g. a method or constructor body. See @tomasBull's answer for an example of where you can do that.

The compiler is trying to parse food_names.add("pizza"); as a declaration, and is getting thoroughly confused.




回答4:


There is another solution

food_names.add(new String("pizza"));



回答5:


Class Example 
{

//**Do not place it here.**
List food_names = new ArrayList();
food_names.add("pizza");

 public static void main(String[] args)
{

//**You should place it here**
List food_names = new ArrayList();
food_names.add("pizza");

}


}



回答6:


I'm not sure you're initializing the ArrayList correctly. Try

ArrayList<String> food_names = new ArrayList<String>();

Also double check you've imported ArrayList. Or try removing the quotation marks around pizza. Disclaimer: I'm probably wrong but I'm laying in bed typing this from my phone, haha. Good luck.



来源:https://stackoverflow.com/questions/5055936/unable-to-add-a-string-to-an-arraylist-misplaced-constructs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!