gpt4 book ai didi

java - 如何在java中检查 boolean 方法的返回值

转载 作者:行者123 更新时间:2023-11-30 02:56:30 26 4
gpt4 key购买 nike

我对 Java 还很陌生,我想做的事情可能看起来很奇怪,但我对 Java 工作原理的了解比实际完成设定的结果更重要。

例如,如果我有一个 boolean 方法:

public class doThings
{

// imagine the intial value of this variable is set
// and or modified using getters and setters between the declaration
// and the following method
private boolean boolVar;


public boolean doSomething()
{
if(boolVar == true)
{
//does things and then returns true
return true;
}
else
{
return false;
}
}
}

我想在另一个类中调用这个方法,就像这样......

public class testDoThings
{

doThings someObject = new doThings;
public static void main(String[] args)
{
someObject.doSomething()
}
}

如何检查(在类 testDoThings 中)该方法是否返回 true 或返回 false 并相应地打印消息,如下所示...

public class testDoThings
{

doThings someObject = new doThings;
public static void main(String[] args)
{

someObject.doSomething()
if (doSomething() returns true) // yes I am aware this is not
//valid
{
// print a statment
}
else if (doSomething() returns false) // yes once again not valid
{
// print a different statement
}
}
}

我知道您可以将这些消息放入包含该方法的类中,但如果我想要根据调用该方法的位置以及调用的内容来获取不同的消息,那么将内容放入原始类方法中并不总是可行去工作。

如果我完全偏离了轨道,请告诉我,如果有人可以向我解释这一点,那就太好了!

最佳答案

你可以这样尝试:

if (someObject.doSomething()) //So if your function returns true then the below statement will be executed
{
// print a statment
}
else //This will check for the false condition of your function
{
// print a different statement
}

关于java - 如何在java中检查 boolean 方法的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37108103/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com