[英]How can i use the return statement of a boolean in another method?
I have a method that returns true or false, 我有一个返回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;
}
How do i use this return statement in another method? 如何在其他方法中使用此return语句? This is what i am trying to do 这就是我想要做的
public void recordVote()
{
if comfirmVotes returns true for X
do this for y
}
If you inspect your confirmVotes method, you will notice that you've already solved this problem:- 如果检查您的confirmVotes方法,您会注意到您已经解决了此问题:
if(answer.equalsIgnoreCase("Yes"))
.equalsIgnoreCase(String s) is a method which returns a boolean, and you've already constructed an if statement based on its return value. .equalsIgnoreCase(String s)是一种返回布尔值的方法,并且您已经基于其返回值构造了一个if语句。 Thus:- 从而:-
if (confirmVotes())
{
// Do whatever
}
Also worthy of note, you can replace:- 同样值得注意的是,您可以替换:-
if(answer.equalsIgnoreCase("Yes"))
return true;
else
return false;
with:- 与:-
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();
}
}
I think your problem is how to call a method belong to the same class from a another method of that class. 我认为您的问题是如何从该类的另一个方法中调用属于同一类的方法。 (Because You have already used a return statement of another method inside your first code block.) (因为您已经在第一个代码块中使用了另一个方法的return语句。)
You can use this keyword for refering to current instance of the class, or if it is call inside a non-static method, you don't need to use that. 您可以使用此关键字来引用该类的当前实例,或者,如果在非静态方法中调用该关键字,则无需使用该关键字。
eg: 例如:
if (this.confirmVotes() == true)
or (if the calling method is a member method (non-static) or called method is a static method)) 或(如果调用方法是成员方法(非静态)或被调用方法是静态方法))
if (confirmVotes() == true) {
Because confirmVotes() method returns true, you can also use if(confirmVotes()) instead of comparing it to boolean true again. 由于confirmVotes()方法返回true,因此您也可以使用if(confirmVotes()),而不是再次将其与布尔值true进行比较。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.