【问题标题】:returning a true or false method返回 true 或 false 方法
【发布时间】:2014-02-26 03:09:58
【问题描述】:
public class Book { 
String title; 
boolean borrowed; 
// Creates a new Book 
public Book(String bookTitle){ 
    bookTitle= "The Da Vinci Code";
} 
// Marks the book as rented 
public void borrowed() { 
    int borrowed= 1;
    // Implement this method 
} 
// Marks the book as not rented 
public void returned() { 
    int returned = 2;
    // Implement this method 
} 
// Returns true if the book is rented, false otherwise 
public boolean isBorrowed(int returned, int borrowed) { 
    if (borrowed < 2 )
    return true;
    else 
    return false;
    // Implement this method 
} 
// Returns the title of the book 
public String getTitle() { 
    String bookTitle= "The Da Vinci Code";
    return bookTitle;
    // Implement this method 
}

public static void main(String[] arguments){ 
    // Small test of the Book class
    int returned= 1;
    int borrowed= 2;
    Book example = new Book("The Da Vinci Code"); 
    System.out.println("Title (should be The Da Vinci Code): " +example.getTitle()); 
    System.out.println("Borrowed? (should be false): " + example.isBorrowed(returned, borrowed)); 
    example.borrowed(); 
    System.out.println("Borrowed? (should be true): " + example.isBorrowed(returned, borrowed)); // should be returning true but it not. It printing false
    example.returned(); 
    System.out.println("Borrowed? (should be false): " + example.isBorrowed(returned, borrowed)); 
} 

我正在做类和方法。我正在做一个书类,它几乎可以工作,但我需要让第二个打印语句打印为真,但我弄错了。我应该怎么做才能解决这个问题?

【问题讨论】:

  • 你似乎不知道自己在做什么。回到绘图板。浏览最基本的教程,here
  • 您的局部变量正在阻止对类字段的访问。删除“int”声明。

标签: java class methods boolean


【解决方案1】:

您在 void 借用了一个新的 int,它与 main 方法中的 int 不同,所以让它成为借用的类 int 的一个属性,不要声明它两次。

【讨论】:

    【解决方案2】:

    您在main() 方法中将局部变量borrowed 设置为2。你调用isBorrowed() 并将这个变量传递给它。然后在isBorrowed() 中,如果borrowed 小于2,则返回true。不是这样,所以返回false。

    您的borrowed() 方法需要将Book 中的borrowed 字段设置为true,而不是设置局部变量。

    您应该了解声明变量和分配变量值之间的区别

    【讨论】:

      猜你喜欢
      • 2012-02-21
      • 1970-01-01
      • 1970-01-01
      • 2019-12-04
      • 1970-01-01
      • 2018-11-09
      • 2011-01-17
      • 2017-09-16
      • 2021-05-17
      相关资源
      最近更新 更多