package shenhui;
import java.util.Scanner;
class book {
// 定义一个book类
String name;
double price;
String author;
double sellprice;
// 以上为book类的属性
book(){
System.out.println("这是默认的构造方法");
}
book(String name,double price,String author){
this.name =name;
this.price =price;
this.author =author;
}
//构造函数book与类名相同,构造函数没有返回值,因此没有返回值数据类型的设定
//构造函数重载,可以根据输入参数的不同调用不同的构造函数
void show() {
System.out.println("书名:" + name);
System.out.println("定价:" + price);
System.out.println("作者:" + author);
}
void normalprice() {
System.out.println(String.format("%.2f", (price * 0.9)));
}
// 不带返回值的方法
// String.format("%.2f", (price*0.9))保留2位输出结果
double vipsellprice(double discount) {
return discount * price;
}
// 带返回值的方法
}
class bookshop {
public static void main(String[] args) {
book books[] = new book[5];
// int a[]=new int[5];仿照之前实例化数组的形式,实例化1个名叫books的数组,数组中每个元素都是book类的,所以下面要每个元素实例化
for (int a = 0; a < books.length; a++) {
books[a] = new book();// 实例化books数组中每个元素为book类型
//System.out.println(book[a]); 传址
}
books[0].name = "JAVA学习记录";
books[0].price = 32.55;
books[0].author = "张三";
books[1].name = "c#学习方法";
books[1].price = 42.81;
books[1].author = "李四";
books[2] =new book("生活的哲学",54.12,"王五");
books[3] =new book("万物有灵且美",32.34,"吉米·哈利");
//给每个对象的属性赋值
System.out.println("本店所有的书如下:");
for (book a : books) {
a.show();
System.out.println("——————————————————————");
}
System.out.println("请输入顾客类型:(normal or vip)");
Scanner in = new Scanner(System.in);
String Customer = in.next();
//in.next() 空格/enter键不作为输入内容
//in.nextLine() 读取一行,空格/enter键也作为输入内容
System.out.println("欢迎"+Customer+"顾客");
if (Customer.equals("normal")) {
for (int a = 0; a < books.length; a++) {
books[a].show();
System.out.print("售价(九折优惠):");
books[a].normalprice();
System.out.println("——————————————————————");
}
}
else if (Customer.equals("vip")) {
for (int b = 0; b < books.length; b++) {
books[b].show();
System.out.println("售价(八折优惠)"
+ String.format("%.2f", books[b].vipsellprice(0.8)));
System.out.println("——————————————————————");
}
}
in.close();
System.out.println("结束");
}
}