[英]How can i use the return statement of a boolean in another method?
我有一个返回true或false的方法,
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;
}
如何在其他方法中使用此return语句? 这就是我想要做的
public void recordVote()
{
if comfirmVotes returns true for X
do this for y
}
如果检查您的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");
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 {
}
}
public void myMethod(){
if(confirmVotes()){
doStuff();
}
else{
doOtherStuff();
}
}
我认为您的问题是如何从该类的另一个方法中调用属于同一类的方法。 (因为您已经在第一个代码块中使用了另一个方法的return语句。)
您可以使用此关键字来引用该类的当前实例,或者,如果在非静态方法中调用该关键字,则无需使用该关键字。
例如:
if (this.confirmVotes() == true)
或(如果调用方法是成员方法(非静态)或被调用方法是静态方法))
if (confirmVotes() == true) {
由于confirmVotes()方法返回true,因此您也可以使用if(confirmVotes()),而不是再次将其与布尔值true进行比较。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.