我的问题就是这样。我试图将字符串声明为特定大小,我排序和所有内容,但唯一有效的是将字符串放在我使用的主类中的main方法中。这令人沮丧,因为我已经尝试了所有我能想到的东西。当我从另一个类导入元素时,为什么元素变得无效?我在移动类中添加了一个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);
这就是我对主要问题的看法,直到问题结束的地方和开始的地方。 任何inpu将不胜感激。谢谢!
答案 0 :(得分:3)
您永远不会初始化moves
内的movesClass
字段。它为null,是引用字段的默认值。如果你想初始化它,你必须这样做:
String[] moves = new String[7];
但即使你这样做,数组的元素仍然是null
,你必须把实际的字符串放在数组中。看来你的useMoves()
是为此而制作的,但它永远不会被调用。无论如何,这种方法有点奇怪。你有一个数组作为参数,你用移动填充然后对它进行排序,但是你返回相同的数组,你已经得到了参数。将Java从一个方法传递给另一个方法或从方法返回时,Java不会复制数组,因此您可以修改作为参数获取的数组。如果您总是希望使用相同的移动初始化moves
字段,那么最好在类的构造函数中执行此操作。静态方法无法访问类的实例字段。