【发布时间】:2020-08-24 11:33:11
【问题描述】:
我已经在 Codecademy 上练习了一段时间的编码,我决定自己玩 ArrayLists。 Codecademy 只向我展示了如何使用 println 来实现我想要打印到控制台的值。相反,我想,如果我想使用构造函数和方法怎么办?在玩了一会儿之后我想出了这个,但由于我仍然是一个初学者,如果我可以更好地优化它以获得相同的结果,我很想知道如何。非常感谢您的宝贵时间!
import java.util.ArrayList;
public class List {
//set variables to be used in constructor and custom method
String itemValue;
int itemIndex;
//declare shoppingList array
ArrayList<String> shoppingList = new ArrayList<String>();
{
//set what is inside the shoppinglist array
shoppingList = new ArrayList<String>();
shoppingList.add("Pumpkin");
shoppingList.add("Carving Kit");
shoppingList.add("Halloween Decorations");
shoppingList.add("Face Paint");
}
public List(String itemName) {
//set the value of what we want to find our index for to itemValue
itemValue = itemName;
}
public void getIndex() {
//sets the index of itemValue to itemIndex then prints the name and index
itemIndex = shoppingList.indexOf(itemValue);
System.out.println("The index of " + itemValue + " is " + itemIndex + "!");
}
public static void main(String[] args) {
//declare shoppingIndex object
List shoppingIndex = new List("Face Paint");
//Calls get index to print our Item name and its index in shoppingList
shoppingIndex.getIndex();
}
}
【问题讨论】:
-
这是一个更适合codereview.stackexchange.com 的问题。祝你好运!
-
非常感谢您提供此链接,不知道该网站存在!我很感激!
标签: java arraylist methods constructor