2016-11-12 54 views
0

我對java還是比較新的。我想用3種不同屬性的角色類型進行遊戲。我爲每種類型使用int值,以便它們的攻擊值是一個範圍,而不僅僅是一個常量值。由於每個字符都有不同的範圍,我想用一個int值替代實際的數字來獲得一個隨機數。這是我的代碼。使用int變量獲取範圍以獲得隨機數

package battleme; 

import java.util.Random; 

/** 
* 
* @author Kitten 
*/ 
class Character { 


String name; 
int life; 
int playerAttacklow; 
int playerAttackhigh; 
int playerDefense; 
int playerLevel; 
int currentXP; 
int currentGold; 



    public Character(String name, int life, int playerAttacklow, 
     int playerAttachhigh, int playerDefense, 
     int playerLevel, int currentXP, int currentGold) { 
} 



public String getName() { 
    return name; 
} 

public void setName(String name) { 
    this.name = name; 
} 

public int getLife() { 
    return life; 
} 

public void setLife(int life) { 
    this.life = life; 
} 

public int getPlayerAttacklow() { 
    return playerAttacklow; 
} 

public void setPlayerAttacklow(int playerAttacklow) { 
    this.playerAttacklow = playerAttacklow; 
} 

public int getPlayerAttackhigh() { 
    return playerAttackhigh; 
} 

public void setPlayerAttackhigh(int playerAttackhigh) { 
    this.playerAttackhigh = playerAttackhigh; 
} 

public int getPlayerDefense() { 
    return playerDefense; 
} 

public void setPlayerDefense(int playerDefense) { 
    this.playerDefense = playerDefense; 
} 

public int getPlayerLevel() { 
    return playerLevel; 
} 

public void setPlayerLevel(int playerLevel) { 
    this.playerLevel = playerLevel; 
} 

public int getCurrentXP() { 
    return currentXP; 
} 

public void setCurrentXP(int currentXP) { 
    this.currentXP = currentXP; 
} 

public int getCurrentGold() { 
    return currentGold; 
} 

public void setCurrentGold(int currentGold) { 
this.currentGold = currentGold; 
} 
//the problem child 
int ActualAttackGen(int playerAttackhigh, int playerAttacklow) { 
    Random rn = new Random(); 
    int randomNum; 

    randomNum= rn.nextInt((playerAttackhigh-playerAttacklow) + 1)+ playerAttacklow ; 


      return randomNum ; 
} 

package battleme; 



public class BattleMe { 

/** 
* @param args the command line arguments 
*/ 
public static void main(String[] args) { 
    // TODO code application logic here 
    Character Warrior = new Character("Warrior", 30, 2, 10, 3, 1, 1, 15); 
    Character Rouge = new Character("Rouge", 25, 3, 6, 2, 1, 1, 15); 
    Character Mage = new Character("Mage", 18, 2, 8, 1, 1, 1, 15);   

    // trying to run the problem child 
    System.out.println(Warrior.ActualAttackGen(Warrior.playerAttackhigh,Warrior.playerAttacklow)); 


} 

} 

每當我嘗試運行這個,我總是得到0的值。請幫助!

回答

0

在你的構造函數,你必須傳遞的值分配給您的字符類的各成員:

public Character(String name, int life, int playerAttacklow, 
    int playerAttachhigh, int playerDefense, 
    int playerLevel, int currentXP, int currentGold) { 
    this.name = name; 
    .... 
} 

BTW:這將是良好的編碼習慣區分成員和參數名。通常一個前綴(或兩者)。例如。成員myName,參數aName。因此,您不必使用「this」引用該成員。:

myName = aName; 
+0

非常感謝!我真誠地感謝它:) – KittenKillzU

+0

所以,請也投我的答案,並接受它作爲有效。 – Heri