解析为if语句的变量

时间:2014-10-02 17:38:05

标签: java variables if-statement

我试图完成我的if语句,我无法将winChance解析为if语句中的变量,如果有人能告诉我hoew将非常感激。 ereor在'破球前的目标是:“+ winChance);'和我最后的winChance方法没有返回双变量'

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

2 个答案:

答案 0 :(得分: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

确保你现在还没有归还任何东西。

答案 1 :(得分:0)

您需要在print语句的“winChance”末尾添加括号以及参数。现在,编译器认为您正在使用变量而不是方法调用。

例如

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方法中返回一个值。

P.S我猜你的意思是在你的winChance方法中使用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