2014-10-02 103 views
-1

即時通訊嘗試完成我的if語句,並且我無法將winChance解析爲if語句中的變量,如果有人能夠向我展示它,將不勝感激。該ereor是'目標之前會破產是:「+永昌);‘我的最後永昌方法沒有返回一個雙變量’解決if語句的變量

import java.util.Scanner; 

public class StockiColeA1Q3 { 

    public static void main(String[] args) { 

    Scanner keyboard = new Scanner(System.in); //scanner 

    System.out.println("What is your first name? "); 
    String first = keyboard.nextLine(); 

    System.out.println("What is your last name? "); 
    String last = keyboard.nextLine(); 

    System.out.println("What is the amount of chips you are starting with, " + first +"?"); 
    int start = keyboard.nextInt(); 

    System.out.println("What is the amount of chips you wish you have ?"); 
    int end = keyboard. nextInt(); 

    System.out.println("What is the probability of each round? \n" + 
         "(A value between 0.0 and 1.0)"); 
    double p = keyboard.nextDouble(); 

    printResult(start,end,p,first,last); 

    }//main 

    public static void printResult(int start, int end, double p, String first, String last) { 

    System.out.println(first + " " + last +": If you start with " + start + " chips\n" + 
         "And do not quit until you have " + end + " chips,\n" + 
         "with the probability of " + p + " of winning each round, \n" + 
         "the chance of reaching your goal before going broke is: " + winChance); 

    }//print results 

    public static double winChance(double start, double end, double p) { 


    if (p==0.5) { 
    System.out.println(start/end); 

    }  
    else if (p>0&&p<1) { 
    System.out.println(1-(Math.pow((1-p)/p, start))/1-(Math.pow((1-p)/p, end))); 

    }//if p isnt 0.5 
    }//win chance 

}//gamblers ruin 
+0

你實際上並沒有聲明一個叫做winChance的變量 – SamTebbs33 2014-10-02 17:42:31

回答

0
if (p==0.5) { 
System.out.println(start/end); 
**return (start/end);** 

}  
else if (p>0&&p<1) { 
System.out.println(1-(Math.pow((1-p)/p, start))/1-(Math.pow((1-p)/p, end))); 
**return (1-(Math.pow((1-p)/p, start))/1-(Math.pow((1-p)/p, end)));** 

}//if p isnt 0.5 

確保您返回的東西,現在你不返回任何東西。

+0

試試這個確保你返回double,否則你會得到一個編譯錯誤。 – brso05 2014-10-02 17:44:55

0

您需要添加括號爲「永昌」結束的打印語句中,與參數一起。現在,編譯器認爲你正在使用一個變量,而不是一個方法調用。

對於示例

System.out.println(first + " " + last +": If you start with " + start + " chips\n" + 
        "And do not quit until you have " + end + " chips,\n" + 
        "with the probability of " + p + " of winning each round, \n" + 
        "the chance of reaching your goal before going broke is: " + winChance(start, end, p)); 

您還需要關注brso05的回答,並在winChance方法中返回一個值。

PS我猜你的意思是使用return代替的System.out.println()在你的文創法,如果是這樣,請使用以下代替:

if (p==0.5) { 
    return start/end; 
}  
else if (p>0&&p<1) { 
    return 1-(Math.pow((1-p)/p, start))/1-(Math.pow((1-p)/p, end)); 
} 

您可能需要閱讀起來更多關於在Java中使用方法,試試這個http://www.tutorialspoint.com/java/java_methods.htm