我的问题就是这样。我试图将字符串声明为特定大小,对所有内容进行排序,但是唯一起作用的是将字符串放入我使用的主类内的main方法中。这很令人沮丧,因为我已经尝试了所有我能想到的东西。当我从另一个类中导入元素时,为什么这些元素变得无效?我在moves类中添加了main方法,然后将其移到那里进行尝试,但无济于事。
这是第一个程序:
import java.util.Arrays;
public class movesClass {
public String[] getMoves() {
return moves;
}
String[] moves;
public static String[] useMove(String[] moves) {
moves[0] = "punch";
moves[1] = "kick";
moves[2] = "defend";
moves[3] = "run";
moves[4] = "inventory";
moves[5] = "rickroll";
moves[6] = "heal";
Arrays.sort(moves);
return moves;
}
}
And the body of the main one:
import java.io.*;
import java.util.*;
public class practiceBattle {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Random rand = new Random();
inventoryClass quant = new inventoryClass();
movesClass mov = new movesClass();
String[] moves = mov.getMoves();
int hp = 0;
int playerHp = 200;
String input = "default";
int damage = 0;
int hitDif = 50; //default
int kickChance1 = 0; //default -- goes into hitChance
int kickChance = kickChance1 - hitDif; //chance to hit
int hitChance1 = 0;
int hitChance = hitChance1 - hitDif;
int runDif = 50; //default
int runChance1 = 0; //default -- goes into runChance
int runChance = runChance1 - runDif; //chance to run
int enemyMinAttack = 0;
int enemyAttack = 0;
int index = 0;
int[] levelArray = {1, 2, 3};
String[] monsterArray = {"GNOLL", "TROLL", "DRAGON"};
String monster = monsterArray[rand.nextInt(monsterArray.length)];
int level = rand.nextInt(levelArray.length) + 1;
if(level == 1)
{
System.out.println("YOUR OPPONENT IS A BABY " + monster + "!");
}
else
{
System.out.println("YOUR OPPONENT IS A LEVEL " + level + " " + monster + "!");
}
if(level == 1)
{
hp = rand.nextInt(20) + 41;
enemyAttack = rand.nextInt(5) + 1;
}
else if(level == 2)
{
hp = rand.nextInt(20) + 91;
enemyAttack = rand.nextInt(6) + 5;
}
else if(level == 3)
{
hp = rand.nextInt(20) + 141;
enemyAttack = rand.nextInt(7) + 10;
}
enemyMinAttack = rand.nextInt(enemyAttack) + 1;
System.out.println("YOUR OPPONENT'S HP IS: " + hp + "\n");
int permEnemyAttack = enemyAttack;
int permEnemyMinAttack = enemyMinAttack;
ext:
while(hp > 0)
{
enemyAttack = permEnemyAttack;
enemyMinAttack = permEnemyMinAttack;
do
{
if(playerHp == 0)
{
System.out.println("YOU HAVE DIED. GAME OVER!\n\n\n");
break ext;
}
else
{
System.out.println("Choose an action:\nkick\npunch\nrun\ndefend\n");
input = scan.nextLine();
index = Arrays.binarySearch(moves, input);
System.out.println(index);
if(index < 0)
{
System.out.println("\n\n\nINVALID INPUT -- TRY AGAIN\n\n\n");
}
}
} while(index < 0);
这就是我要解决的主要问题,直到问题的根源和开始的地方。
任何输入将不胜感激。谢谢!
最佳答案
您永远不会在moves
内初始化movesClass
字段。它为null,这是参考字段的默认值。如果要初始化它,则必须执行以下操作:
String[] moves = new String[7];
但是即使这样做,数组的元素仍将是
null
,并且必须将实际的Strings放入数组中。看来您的useMoves()
是为此而设计的,但从未调用过。无论如何,这种方法有点奇怪。您有一个数组作为自变量,先填充移动然后对其进行排序,但是随后返回相同的数组,您已经将其作为参数。当您将数组从一个方法传递给另一方法或从方法返回它们时,Java不会复制数组,因此您可以修改作为参数获取的数组。如果您总是想用相同的动作初始化moves
字段,那么最好在类的构造函数中执行此操作。静态方法无权访问类实例的字段。