編輯:我想將wG1 ... wG5的值在Main類中傳遞給rarityType(),該值等於5個參數。我希望這些傳入的參數在int []中使用,它定義了罕見[]中項目的權重。從數組中設置隨機字符串的參數:例外n <= 0
硬編碼的值代入函數(第3行)的工作原理按預期:
public String rarityType() {
String rare[] = {"Common", "Uncommon", "Rare", "Epic", "Legendary"};
int[] a = {64, 32, 24, 4, 1};
int sum = 0;
for (int i : a)
sum += i;
int s = r.nextInt(sum);
int prev_value = 0;
int current_max_value;
int found_index = -1;
for (int i = 0; i < a.length; i++) {
current_max_value = prev_value + a[i];
boolean found = (s >= prev_value && s < current_max_value);
if (found) {
found_index = i;
break;
}
prev_value = current_max_value;
}
rarityType()不在主實例化,它的值是通過吸氣劑檢索到:
Weapon weapon = new Weapon();
String weaponRarity = weapon.getWeaponRarity();
並在類中:
private String weaponRarity = rarityType();
但我想能夠修改這些值從主。
。
我想在Main中爲返回加權隨機字符串的類設置參數。當我在課堂上硬編碼參數時,它按預期工作。
異常告訴我,隨機生成器返回null,因爲它沒有傳遞任何參數。我試圖在課堂上創建setter,並在Main中定義它們,但無濟於事。我的問題是,我如何將參數傳遞給我在Main中實例化的類中的函數?感謝您的任何指導! 注意:在Main中我不能擁有這個類的構造函數,因爲它們是依賴於此函數返回字符串的類中的其他函數。
主要的代碼片段:
Weapon weapon = new Weapon();
weapon.wG1 = 1;
weapon.wG2 = 1;
weapon.wG3 = 1;
weapon.wG4 = 1;
weapon.wG5 = 1000;
類的代碼片段:
public class Weapon {
public int wG1,wG2,wG3,wG4,wG5;
private Random r = new Random();
private String weaponRarity = rarityType(wG1,wG2,wG3,wG4,wG5);
public String rarityType(int w1, int w2, int w3, int w4, int w5) {
String rare[] = {"Common", "Uncommon", "Rare", "Epic", "Legendary"};
int[] a = {w1, w2, w3, w4, w5};
int sum = 0;
for (int i : a)
sum += i;
int s = r.nextInt(sum); //line 100
int prev_value = 0;
int current_max_value;
int found_index = -1;
for (int i = 0; i < a.length; i++) {
current_max_value = prev_value + a[i];
boolean found = (s >= prev_value && s < current_max_value);
if (found) {
found_index = i;
break;
}
prev_value = current_max_value;
}
String selection = "unknown";
if (found_index != -1) {
selection = rare[found_index];
}
return selection;
}
這個版本的代碼會拋出異常:
Caused by: java.lang.IllegalArgumentException: n <= 0: 0 at
net.zingrook.mobiloot.Weapon.rarityType(Weapon.java:100)
好的,你爲'w1','w2'等傳入了什麼值?不,例外*不會告訴你「隨機生成器返回null」 - 它告訴你它拋出了一個異常,因爲你傳入了一個無效的參數。 –
如果你的問題是關於如何將參數傳遞給方法,那麼幾乎所有的方法體在這裏都是不相關的。請注意,你沒有展示你如何調用方法 - 而*這是你要傳遞參數的地方。 –