我有一个简单的问题。我有两种方法:返回和借用。每当我尝试
借用它继续返回true,每当我尝试返回它时总是返回false。
当我尝试调试代码时,似乎程序经历了真实然后
立即为假。
这是借用方法:
public boolean Borrow (String TitleOrAuthor,int id){
int count = 0;
int b1 = 0;
int BookCount [] = new int [b1];
for (int i=0;i<Bcount;i++){
if(Booklist[i].getTitle().equals(TitleOrAuthor)){
for(int j=0;j<b1;j++){
BookCount = Booklist[i].getCopies();
BookCount [j] = id;
b1++;
}
return true;
}
else
return false;
}
for (int i=0;i<Ucount;i++){
if (users[i].getID()==id){
if (users[i].getOccupation()=='S'){
count = users[i].getNumBorrowed();
if (count<=3)
count++;
return true;
}
else if (count>3)
return false;
if (users[i].getOccupation()=='P'){
count = users[i].getNumBorrowed();
if (count<=5)
count++;
return true;
}
else if (count>5)
return false;
}
}
return false;
}
这是返回方法:
public boolean Return (String TitleOrAuthor, int id){
int count = 0;
int b1 =0;
int BookCount [] = new int [b1];
for (int i=0;i<Bcount;i++){
if(Booklist[i].getTitle().equals(TitleOrAuthor))
for(int j=0;j<b1;j++){
BookCount = Booklist[i].getCopies();
BookCount[j] = --id;
b1--;
if(Booklist[i].getTitle()!=TitleOrAuthor){
return false;
}
}
}
for (int i=0;i<Ucount;i++){
if (users[i].getID()==id){
if(users[i].getNumBorrowed()>0)
count = users[i].getNumBorrowed();
count--;
if(users[i].getNumBorrowed()==0){
return false;
}
}
}
return true;
}
*注意:BookCount数组会在用户借用时保存用户的ID。
谢谢。
**编辑:这里主要是调用方法:借用:
private void BorrowBtnActionPerformed(ActionEvent evt) {
int a = Integer.parseInt(LogInField.getText());
L1.Borrow (OptionField.getText(),a);
if (L1.Borrow (OptionField.getText(),a)==true){
JOptionPane.showMessageDialog(null, "The book was borrowed succesfully");
}
else{
JOptionPane.showMessageDialog(null, "You reached the maximum number");
}
}
返回:
private void ReturnBtnActionPerformed(ActionEvent evt) {
int a = Integer.parseInt(LogInField.getText());
L1.Return (OptionField.getText(),a);
if (L1.Return (OptionField.getText(),a)==true){
JOptionPane.showMessageDialog(null, "The book was returned succesfully");
}
else{
JOptionPane.showMessageDialog(null, "You cannot return a book you did not borrow");
}
}
答案 0 :(得分:0)
您的代码存在一些问题,其中一些问题已在评论中提及,例如
Borrow
b1
始终为0,因此循环for(int j = 0; j < b1; j++) {}
永远不会运行Borrow
中,您不更新用户的洞穴数,因此users[i].getNumBorrowed()
将始终返回0 titleOrAuthor
而不是TitleOrAuthor
),可能更容易区分类和变量以及其他人理解您的代码并提供帮助Borrow
中,你会遍历书籍,如果标题匹配,你将所有副本设置为相同的id,这似乎是一个bug Borrow
的第一个参数(同样惯例称它应该是borrow()
)被称为TitleOrAuthor
但你只检查标题,所以当提供作者时没有匹配Return
中,您还有b1 = 0
和for(int j = 0; j < b1; j++) {}
问题Return
中减少循环变量的上限b1
,这样你就可以比可能假设的更早结束循环(假设上面的问题已经解决)Return
中,您在循环的每次迭代中减少id
,这不符合Borrow
中使用的相同ID,但仍然可能是错误Return
中,您还会减少方法完成后丢失的局部变量count