(下面的完整代码)我刚刚提交了一个课堂实验室,我们必须制作一个描述某本书的课程。我不知道如何做两件事。1. 如果有人为 'pages' 或 'suggestedRetailPrice' 输入小于零的值,则该值必须设置为零。在此代码中,即使该值为正,该值也设置为 0。在里面:
if ( pages <= 0 )
{
pages = 0;
}
如果我将第二个“0”设置为不同的数字,则代码,例如:
if ( pages <= 0 )
{
pages = 1;
}
那么你为'pages'输入的任何值都会是1。但是如果你输入的值是负数,它不应该是1吗?我不明白我做错了什么。
我想不通的第二件事是在代码的底部,我们必须显示所有信息。我的老师希望我们用“是”或“否”而不是“真”或“假”来显示这本书是否是平装本。我该怎么做呢?我试着像这样写一个 if/else 语句: System.out.println("Paperback : " + if (paperback = true) {Yes} if (paperback = false) {no}; )
没用,想不通。请参阅下面的完整代码。
public class Book {
// Instance variables
private String title;
private String author;
private int isbn;
private int pages;
private boolean paperback;
private int suggestedRetailPrice;
/**
* Default contructor
*/
public Book() {
title = "";
author = "";
isbn = 0;
pages = 0;
paperback = false;
suggestedRetailPrice = 0;
}
/**
* book information
*/
public Book(String whatIsTitle, String whoIsAuthor, int isbnCode,
int numberOfPages, boolean isItPaperback,
int theSuggestedRetailPrice) {
title = whatIsTitle;
author = whoIsAuthor;
isbn = isbnCode;
if (pages <= 0) {
pages = 0;
} else {
pages = numberOfPages;
}
paperback = isItPaperback;
if (suggestedRetailPrice <= 0) {
suggestedRetailPrice = 0;
} else {
suggestedRetailPrice = theSuggestedRetailPrice;
}
}
/**
* @return title
*/
public String getTitle() {
return title;
}
/**
* @return author
*/
public String getAuthor() {
return author;
}
/**
* @return isbn
*/
public int getIsbn() {
return isbn;
}
/**
* @return pages
*/
public int getPages() {
return pages;
}
/**
* @return paperback
*/
public boolean getPaperback() {
return paperback;
}
/**
* @return suggestedRetailPrice
*/
public int getSuggestedRetailPrice() {
return suggestedRetailPrice;
}
/**
* title
*/
public void setTitle(String whatIsTitle) {
title = whatIsTitle;
}
/**
* author
*/
public void setAuthor(String whoIsAuthor) {
author = whoIsAuthor;
}
/**
* isbn code
*/
public void setIsbn(int isbnCode) {
isbn = isbnCode;
}
/**
* number of pages
*/
public void setPages(int numberOfPages) {
if (pages <= 0) {
pages = 0;
} else {
pages = numberOfPages;
}
}
/**
* is it paperback
*/
public void setPaperback(boolean isItPaperback) {
paperback = isItPaperback;
}
/**
* suggested retail price
*/
public void setSuggestedRetailPrice(int theSuggestedRetailPrice) {
if (suggestedRetailPrice <= 0) {
suggestedRetailPrice = 0;
} else {
suggestedRetailPrice = theSuggestedRetailPrice;
}
}
/**
* displays information
*/
public void displayBook() {
System.out.println("Title : " + title);
System.out.println("Author : " + author);
System.out.println("ISBN : " + isbn);
System.out.println("Pages : " + pages);
System.out.println("Paperback : " + paperback);
System.out.println("Suggested price : " + suggestedRetailPrice);
}
}