/*
Book类
*/
public class Book {
private String title;//书名
private String pDate;//出版日期
private int words;//字数
//计算价格的price()方法
public void price() throws ParseException {
//构造一个SimpleDateFormat使用给定的模式和默认的日期格式yyyy-MM-dd
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
//解析:从string到Date
Date date=simpleDateFormat.parse(pDate);
//构造一个SimpleDateFormat使用给定的模式和默认的日期格式MM
SimpleDateFormat m=new SimpleDateFormat("MM");
//格式化:从Date到String,获取月份
String month=m.format(date);
String flag="06";//将6月份设为比较对象
float price;//价格
/*
大于flag,返回值result>0
等于flag,返回值result=0
小于flag,返回值result<0
*/
int result=month.compareTo(flag);
if (result>0){
price= (float) (words/1000*35*1.18);
}else {
price= (float) (words/1000*35*1.2);
}
//System.out.println(result);
System.out.println("这本书的单价为:"+price);
}
//get/set方法
public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; }
public String getpDate() { return pDate; }
public void setpDate(String pDate) { this.pDate = pDate; }
public int getWords() { return words; }
public void setWords(int words) { this.words = words; }
}
/*
BookMain类实例化Book对象
*/
public class BookMain {
public static void main(String[] args) throws ParseException {
//创建Book类对象
Book b=new Book();
//键盘录入数据
Scanner sc=new Scanner(System.in);
System.out.println("输入书名,出版日期,字数并用空格隔开:");
//录入书名
String title=sc.next();
b.setTitle(title);
//录入出版日期
String pdate=sc.next();
b.setpDate(pdate);
//录入字数
int words=sc.nextInt();
b.setWords(words);
sc.nextLine();//换行停止录入
b.price();//调用price()方法
}
}
运行结果: