我已经创建了我的类命令
的对象Commands commands = new Commands();
但是,我需要访问该方法中的数组,不知道该怎么做。
package com.PenguinGaming;
import java.util.Scanner;
public class Player {
public void User(){
Commands commands = new Commands();
int Maxlife = 25;
int life = 25;
int turns = 0;
//Starting player location
int playerX = 4;
int playerY = 4;
Scanner scanner = new Scanner(System.in);
String input = null;
while(life > 1){
System.out.println("Player life: " + life + "/" + Maxlife);
input = scanner.nextLine();
input = input.toLowerCase();
life -= 1;
for(int i = 0; i == 30; i++){
turns++;
if(turns == 30){
Maxlife += 5;
}
}
if (input.equals(commands[0])) {
// give description for player location
System.out.println(locations[playerX][playerY]);
}
if(input.equals(commands[1])){
//Go north
System.out.println(locations[playerX][playerY+1]);
playerY += 1;
}
if(input.equals(commands[2])){
//Go east
System.out.println(locations[playerX+1][playerY]);
playerX += 1;
}
if(input.equals(commands[3])){
//Go south
System.out.println(locations[playerX][playerY-1]);
playerY -= 1;
}
if(input.equals(commands[4])){
//Go west
System.out.println(locations[playerX-1][playerY]);
playerX -= 1;
}
if(input.equals(commands[5])){
break;
}
if(life <= 0){
System.out.println("Looks like you have starved, better luck next game");
break;
}
else
System.out.println("You can not move in that direction");
}
System.exit(0);
}
}
package com.PenguinGaming;
public class Commands {
/*
* Command list:
* - investigate (advanced description)
* - go north
* - go south
* - go west
* - go east
* - pick up
* - eat
* - drink from
* - drink object
* - climb up/down
* - burn
* - use object
* - attack
* - defend
* - description (basic description)
* - read
* - life
* - help (brings up command list)
*/
public void commandlist(){
String[] commands = new String[6];
commands[0] = "investigate";
commands[1] = "go north";
commands[2] = "go east";
commands[3] = "go south";
commands[4] = "go west";
commands[5] = "terminate game";
}
}
答案 0 :(得分:0)
如果您想稍微清理一下代码,可以这样做:
public String[] commandlist()
{
return new String[]{"investigate", "go north", "go east", "go south", "go west", "terminate game"};
}
答案 1 :(得分:0)
Java已经存储了定义良好的常量值集。它被称为enum
public enum Commands {
INVESTIGATE("investigate"),
GO_NORTH("go north"),
GO_EAST("go east"),
...
}
等等。
通过这种方式,您可以将命令导入到您编写的类中,并通过返回set的Commands.values()
获取其所有值,因此无论您想要什么,都可以迭代它。这样一来,如果你发现需要添加另一个命令,你只能在一个地方进行操作,因为你操作,检查这些值的相等性等。
我忘了提到这样做,你不必手动创建对象命令。