对于我来说,如何在方法内部使用布尔值以及如何将其设置为false尚不十分清楚。通常,如果在方法内部使用变量,则将其分配给局部变量,是否对布尔值执行相同的操作,或者只是使用并更改它们。
我们为什么要为属性分配局部变量?如果不这样做会发生什么?
如何将设置器用作布尔值?
在有人借书后如何减小arraylist的大小?
public class Governance{
ArrayList<Intenger> Books=new ArrayList<Integer>(10);
private boolean active = true;
public void borrowBook{
/** does I assign active to a local variable? why do we assign attributes
to a local variable? what happens if we dont?why I cant just use and
initialize (e.g. set a value) the attribute as a I defined(best practices)**//
boolean checkStatus = isActive(); //correct?
if(Books.isEmpty()){
//how to I set active to false (best practices)
checkStatus = myFunction(); //correct or are there better ways to do it?
}
else if(!Books.isEmpty() && isActive){
System.out.println("You can borrow that book");
else{
System.out.println("You can not borrow that book");
}
}
public static boolean myFunction(){
return false;
}
public boolean isActive() {
return active;
}
//what is a case where I use this and how?
public void setActive(boolean active) {
this.active = active;
}
}
答案 0 :(得分:2)
boolean
是原始数据类型。您可以像其他基元一样分配它:
boolean active = true; active = false;
active == true
if(active) { // do stuff }
不需要active == true
active
中的Governance
具有覆盖整个类的范围。yourGovernanceInstance.setActive(false);
因此我们将此类实例的active
属性更改为false
。我很难使用格式化程序共享代码,请参见this link以获取简洁的版本。仅在目标链接过期时才在下方。
import java.util.ArrayList;
import java.util.List;
import java.lang.Integer;
public class Governance {
// usually we write variables in lower case.
private List<Integer> books = new ArrayList<Integer>();
// private member. To change it's value it's best practice to call setters and getters to change the value.
private boolean active = true;
public void borrowBook() {
if(books.isEmpty()){
// I use "this" to refer to this class's method "isActive()"
} else if(!books.isEmpty() && this.isActive()){
System.out.println("You can borrow that book");
} else {
System.out.println("You can not borrow that book");
}
}
public boolean isActive() {
return active;
}
// You habe a class that has many Governance instances, e.g.
// Governance myGov = new Governance();
// myGov is no more active, so you call: myGov.setActive(false);
public void setActive(boolean active) {
this.active = active;
}
}
您也可以只使用else if(!books.isEmpty() && active)
。
取决于。通常,ArrayList
在您的上下文中将包含Book
个对象。您必须确定某人想拿的书。
公共课本{ 私人int ID; 私有字符串标题; 私有布尔活动状态; </ p>
public Book(int id, String title, boolean active) {
this.id = id;
this.title = title;
this.active = active;
}
// Setters and Getters
}
在您的Governance
类中:
public boolean canBorrowBookWithId(int id) {
Book bookToBeBorrowed = books.get(id);
boolean canBorrow = true;
// If book can is active, it can't be borrowed.
if(bookToBeBorrowed.IsActive()){
canBorrow = false;
} else {
// If not; set it to be and lend it out :-)
bookToBeBorrowed.setActive(true);
}
return canBorrow;
}
旁注:canBorrowBookWithId()检查该书是否可用以及 设置它的状态。通过干净的代码,一种方法只能做一个 一次完成这些操作!
您正在尝试学习Object oriented programming
,这很难开始,但是最终您会继续::)