【发布时间】:2015-02-28 10:43:46
【问题描述】:
我已经创建了我的类 Commands 的对象
Commands commands = new Commands();
但是,我需要访问该方法中的数组,不知道该怎么做。
Player.java
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);
}
}
Commands.java
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";
}
}
【问题讨论】:
-
您想在
commandlist()中访问commands?将返回类型改为String[],返回commands。 -
谢谢八月,问题似乎已经解决了。
-
您不希望您的命令永久存在于某个地方吗?每次有人需要命令列表时,您是否必须创建该 String[] ?它会改变吗?如果没有,则将其设为 private static final 并编写返回命令的 getter 方法。
-
还有一个约定,将包命名为全部小写。