java 调用布尔方法,头或尾

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26653355/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 10:19:59  来源:igfitidea点击:

calling boolean method, heads or tails

javaboolean

提问by Gianna Caruso

I'm wrote a method to simulate a coin toss, however, I do not know how to call this method in the main. Tips would really be appreciated! (Here is the method, I didn't post the entire code because there are 8 other methods in this code).

我写了一个方法来模拟抛硬币,但是,我不知道如何在 main.js 中调用这个方法。提示将不胜感激!(这是方法,我没有发布整个代码,因为此代码中还有 8 个其他方法)。

 public static boolean headsOrTails()
 {
   boolean coinState;
   if (Math.random() < 0.5) {//heads 50% of the time 
     coinState = true; //heads
   }
   else {    
     coinState = false; //tails
   }
   return coinState;
 }

回答by NewUser

Try this:

试试这个:

boolean isHead = headsOrTails();
if(isHead){
     System.out.println("Heads");
}else{
     System.out.println("Tails");
}

if value of isHead is trueyou have a Head :)

如果 isHead 的值是true你有一个 Head :)

回答by DeepInJava

You should call like :

你应该像这样调用:

public class Abc {

   public static void main(String[] args) {

       System.out.println(headsOrTails());
   }

   public static boolean headsOrTails() {

       boolean coinState;
       if (Math.random() < 0.5) {//heads 50% of the time 
          coinState = true; //heads
       } else {    
          coinState = false; //tails
       }
       return coinState;
   }

}

and it will print the output of the function as trueor false.

它会将函数的输出打印为truefalse

回答by pheamit

You can also improve readability of your code by shortening the boolean evaluation (like Boann mentioned):

您还可以通过缩短布尔评估(如 Boann 提到的)来提高代码的可读性:

public class CoinToss {

    public static void main(String[] args) {
        headsOrTails();
    }

    public static boolean headsOrTails() {
        return Math.random() < 0.5;
    }
}