线程中的异常,在java.util.random.nextInt和main

时间:2016-01-07 15:59:23

标签: java

作为Java的新手,我在使用文本冒险游戏时遇到了麻烦,而且当我处理它时,我意识到我无法运行它。我搜索过Google,看过这里,但没有找到解决方法来解决这个问题。

这是我的错误:

Exception in thread "main" java.lang.IllegalArgumentException: bound must be positive
at java.util.Random.nextInt(Random.java:388)
at iproject.IProject.main(IProject.java:47)

这是我的代码:

package iproject;

import java.util.Random;
import java.util.Scanner;

/**
 *
 * @author twinbranch*/
public class IProject {

/**
 *
 * @param args
 */
public static void main (String[] args) {

Scanner in = new Scanner(System.in);
Random rand = new Random();


String[] enemies = {  };
int maxEnemyHealth = 75;
int enemyAttackDamage = 25;


int health = 100; 
int attackDamage = 50;
int numHealthPots = 3;
int healthPotionHealAmount = 30;
int healthPotionDropChance = 33; //Percentage

boolean running = true; {

GAME:
while (running) {
System.out.println();

int enemyHealth = rand.nextInt(maxEnemyHealth);
String enemy = enemies[rand.nextInt(enemies.length)];
System.out.println("\t# " + enemy + "has appeared! #\n");

第二个错误:

public int nextInt(int bound) {
if (bound <= 0)
throw new IllegalArgumentException(BadBound);

我不想为此发布整个代码,因为它将占用大约400行。

所以,我最初的问题是,有没有人知道我的代码有什么问题?我用这段代码犯了什么错误。

2 个答案:

答案 0 :(得分:1)

问题是enemies.length为零。

答案 1 :(得分:0)

问题是敌人是空的,你需要定义它。 enemies.length = 0因此

// will never work unless enemies is initialized and enemies.length > 0.
String enemy = enemies[rand.nextInt(enemies.length)];

所以考虑并确保敌人的初始化如下:

String[] enemies = {"A","B"}; // however way you want it to be