[英]Returning an int value from a method java
我對Java還是很陌生,但是我正在嘗試使用我有限的知識來模擬手指游戲“ Sticks”。 這可能不是最整潔的方法,但是如果您要建議我做某事,請鏈接說明該事情是什么的頁面,我會閱讀。
好的,所以當我調用一個方法來確定輪到誰並嘗試將“ count”的值返回到5時,問題基本上就出現了,但是它沒有返回到main()
public static int TurnCalcBB(int PLH, int PRH, int BRH, int BLH, int Death)
{
//Attacking with bot Right hand
Random botAtk = new Random();
if(botAtk.nextInt(2) == 1 && PRH <= 5)
{
PRH = BRH + PRH;
JOptionPane.showMessageDialog(null,"Your right hand is now at " + PRH);
return PRH;
} else if(botAtk.nextInt(2) == 0 && PLH <= 5){
PLH = BRH + PLH;
JOptionPane.showMessageDialog(null, "Your left hand is now at " + PLH);
return PLH;
}
return Death;
}
死在那兒是因為我遇到一個錯誤,告訴我我總是需要返回SOMETHING,所以我正在返回一個靜態值。
基本上,問題是讓PLH(玩家左手)或PRH(玩家右手)返回到主菜單。 如果我沒看錯,它們應該以初始變量名稱(PL和PR)返回,並且返回值正確嗎? 如果沒有,我該如何解決?
代碼比這大得多,並且這個問題在整個程序中都發生,因此,我僅展示一種方法,並假設它們都是同一問題。 方法幾乎都是一樣的。
另外,雖然我已經輸入了一個問題,但是nextInt()是執行隨機數生成器的最佳方法嗎? 當我將其命名為nextInt(1)時,它專門攻擊左手,而當我將其切換為nextInt(2)時,它同時在攻擊左手,但有時代碼會“崩潰”(崩潰的意思是它會生成除If語句所查找內容之外的數字)。 我顯然需要生成1或2(如果計數為0,則生成0和1)。
您可以將代碼更改為
public static Integer TurnCalcBB(int PLH, int PRH, int BRH, int BLH, int Death)
{
//Attacking with bot Right hand
Random botAtk = new Random();
if(botAtk.nextInt(2) == 1 && PRH <= 5)
{
PRH = BRH + PRH;
JOptionPane.showMessageDialog(null,"Your right hand is now at " + PRH);
return PRH;
} else if(botAtk.nextInt(2) == 0 && PLH <= 5){
PLH = BRH + PLH;
JOptionPane.showMessageDialog(null, "Your left hand is now at " + PLH);
return PLH;
}
return null;
}
注意:請確保您首先檢查在調用此函數的空值。
您兩次生成隨機數,這就是為什么您可以觀察“奇怪”行為的原因。
Random botAtk = new Random();
if(botAtk.nextInt(2) == 1 && PRH <= 5) {
...
}
else if(botAtk.nextInt(2) == 0 && PLH <= 5) {
...
}
嘗試僅生成一次隨機數:
Random botAtk = new Random();
boolean right = botAtk.nextInt(2) == 1; // flip coin only once
if(right && PRH <= 5) {
...
}
else if(!right && PLH <= 5) {
...
}
我知道答案不會被接受,因為有一個被接受的答案,但是:
我懷疑您對Java中傳遞的方法參數有錯誤的理解。 我從您的問題和評論中讀到的是,您希望它能起作用:
public static int psInt = 0;
static void main() {
int someNumber = 1;
int someOtherNumber = 5;
method1( someNumber, someOtherNumber );
// You expect "someNumber" to be 6 right now.
// But in fact, the value will be unchanged.
// What WILL work: psInt is 0 now
method3(); // this method will modify the static class var
// psInt is 5 now.
}
static void method1( int numParam, int someothervalue ){
numParam = numParam + someothervalue;
}
static void method2( int someNumber, int someothervalue ){
someNumber = someNumber + someothervalue; // <- same name won't work either!
}
public static void method3(){
psInt = 5;
}
但是在Java方法中,參數是通過值傳遞的。 那就是:副本! 因此,無論您如何命名變量和參數,這里都永遠不會有“ out”參數。
您可以做什么:
在您的情況下,4.沒有太大意義,因為您不知道它是新的右手值還是左手值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.