【问题标题】:How can i use the return statement of a boolean in another method?如何在另一种方法中使用布尔值的返回语句?
【发布时间】:2011-12-05 08:04:52
【问题描述】:

我有一个返回真假的方法,

public boolean confirmVotes()
{
System.out.println("Your vote for President is:" + getVotes() );
System.out.println("your vote for Vice President is:" + getVotes());
System.out.println("Is this correct? Yes or No?");
Scanner keyboard = new Scanner(System.in);
String answer = keyboard.nextLine();
if (answer.equalsIgnoreCase("Yes"))
    return true;
 else 
   return false;
}

如何在另一种方法中使用此返回语句?这就是我想做的事情

 public void recordVote()
{
        if  comfirmVotes returns true for X
             do this for y

}

【问题讨论】:

  • 您已经在第一个代码块中使用了另一个方法的 return 语句(在 if 条件下)

标签: java class methods boolean


【解决方案1】:

如果你检查你的 confirmVotes 方法,你会注意到你已经解决了这个问题:-

if(answer.equalsIgnoreCase("Yes"))

.equalsIgnoreCase(String s) 是一个返回布尔值的方法,并且您已经根据其返回值构造了一个 if 语句。因此:-

if (confirmVotes())
{
  // Do whatever
}

另外值得注意的是,可以替换:-

if(answer.equalsIgnoreCase("Yes"))
  return true;
else
  return false;

与:-

return answer.equalsIgnoreCase("Yes");

【讨论】:

  • 这个问题被标记为作业。这样做的想法是,不给发帖人完整的答案,而是为他指明正确的方向。
  • +1 指出您可以在没有 if 语句的情况下使用布尔表达式。
  • @nfechner:我通常同意你的观点,但是当答案像if (confirmVotes()) 这样微不足道时,很难为某人指明正确的方向。特别是因为 Iain 将其比作 OP 已经以相同方式使用过的功能。 +1
  • 是的,一样。我会发现暗示某人解决一个非常简单的语法问题有点傲慢。认为最好给出答案,然后展示几个直接使用方法返回值的类似案例。
【解决方案2】:
public void recordVote() {
    if (confirmVotes()) { // your method should return true. if it does, it will process the if block, if not you can do stuff on the else block

    } else {

    }
} 

【讨论】:

    【解决方案3】:
    public void myMethod(){
        if(confirmVotes()){
            doStuff();
        }
        else{
            doOtherStuff();
        }
    }
    

    【讨论】:

      【解决方案4】:

      我认为您的问题是如何从该类的另一个方法调用属于同一类的方法。 (因为您已经在第一个代码块中使用了另一个方法的 return 语句。)

      您可以使用 this 关键字来引用该类的当前实例,或者如果它在非静态方法中调用,则不需要使用它。

      例如:

      if (this.confirmVotes() == true)
      

      或者(如果调用方法是成员方法(非静态)或者被调用方法是静态方法)

      if (confirmVotes() == true) {
      

      因为 confirmVotes() 方法返回 true,您也可以使用 if(confirmVotes()) 代替再次将其与 boolean true 进行比较。

      【讨论】:

        猜你喜欢
        • 2022-11-11
        • 2013-10-01
        • 2013-12-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-23
        • 2012-08-16
        • 2014-12-19
        相关资源
        最近更新 更多