以下是代码:
public void play() {
Action action;
Place place = getPlace(0);
Item item = new Item("placeholder","a placeholder");
Scanner scanner = new Scanner(System.in);
String text;
System.out.println(getDescription());
while (null != place) {
System.out.println(place.getDescription());
place.printItemDescription();
text = scanner.nextLine();
action = getAction(text, place);
if (text.startsWith("pick up")){
String obtain[] = text.split(" ");
label = obtain[2];
for (int i=0; i<place.itemList.size(); i++){
if (label.equals(place.itemList.get(i).getLabel())){
itemList.add(place.itemList.get(i));
place.itemList.remove(place.itemList.get(i));
}else{System.out.println("There's no " + label + " in this place.");}
}
}
else if (text.startsWith("put down")){
String remove[] = text.split(" ");
label = remove[2];
for (int i=0; i<itemList.size(); i++){
if (label.equals(itemList.get(i).getLabel())){
place.itemList.add(itemList.get(i));
itemList.remove(i);
}//else{System.out.println("Not a valid action");} Not yet working
}
}
else if (text.startsWith("inventory")){
System.out.println("Your inventory contains:");
for (int i=0; i<itemList.size(); i++){
System.out.println(itemList.get(i).getLabel());
}
}
else if (null != action) {
if (checkReq(action) && checkForbidden(action)){
System.out.println(action.getDescription());
place = action.getNext();
}
else if(!checkReq(action)){
System.out.println("You do not have the required item.");
}
else if(!checkForbidden(action)){
System.out.println("You have something that you cannot bring with you.");
}
}
}
}
这是我正在研究的文字游戏的片段。我有Place,Action和Item的课程。我试图创建方法放在else和if else语句下,而不是:
if (text.startsWith("pick up")){
String obtain[] = text.split(" ");
label = obtain[2];
for (int i=0; i<place.itemList.size(); i++){
if (label.equals(place.itemList.get(i).getLabel())){
itemList.add(place.itemList.get(i));
place.itemList.remove(place.itemList.get(i));
}else{System.out.println("There's no " + label + " in this
place");}
我只想:
if (text.startsWith("pick up")){pickUp(text);}
其中pick是我编写的方法,其中包含上述if语句中的所有代码。我想这样做,所以代码更清晰,我可以单元测试这些方法,而不是试图单元测试这个相当膨胀的play()方法。
我遇到的问题是局部变量。我知道我无法通过其他方法访问它们。我认为我可以使它们成为全局变量,虽然这对大多数都有用,但它并不适用于地方,因为随着while循环的运行,地方会发生变化。所以我被卡住了,我想知道他们是不是这样做的方式,或者我是否以错误的方式看待这个。