2016-01-07 61 views
-5

作爲Java的一個新的初學者,我有一個文字冒險遊戲麻煩,因爲我在這工作,我才意識到我是無法運行它。我搜索了Google,看了看,發現如何解決這個問題沒有答案。異常的線程,綁定必須在java.util.random.nextInt是正的,主要

這裏是我的錯誤:

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行。

所以,我最初的問題是,有人知道我的代碼有什麼問題嗎?我用這段代碼做了什麼錯誤。

回答

1

的問題是,enemies.length爲零。

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 
相關問題