Java中的foreach循环
1,语法:
for(元素:数组){
}
2,用法:
String []array={"aa","bb","cc"};
for(String s:array){
System.out.println(s);
}
User[]users={user1,user2,user3};
for(User user:users){
System.out.println(user);
}
Java中小数的格式化:DecimalFormat
1,创建对象:DecaimalFormat df=new DecimalFormat("#0.00");//保留2位小数,会四舍五入的
2,调用format方法进行格式化,返回String
String = df.format(double);
-----------------------------------------------------------------
1,实现循环购书功能
(1)for------->while
(2)OrderItem[]数组尽量给大些
2,购买相同的书籍,数量进行叠加
(1)使用循环检查数组是是否存在书籍信息,存在则叠加数量,否则添加到数组中
(2)数组采用传址引用方式
3,解决购买时图书编号、图书价格的输入问题
(1)输入不存在的编号
(2)非法输入
4,解决库存量显示问题
(1)库存为0的书籍不显示
(2)库存不足不能购买
(3)购买成功后更新库存
图书类
public class Book {
private int bookId;//图书编号
private String bookName;//图书名称
private double price;//图书单价
private int storage;//库存数量
//无参构造
public Book() {
super();
}
//带参构造
public Book(int bookId, String bookName, double price, int storage) {
super();
this.bookId = bookId;
this.bookName = bookName;
this.price = price;
this.storage = storage;
}
public int getBookId() {
return bookId;
}
public void setBookId(int bookId) {
this.bookId = bookId;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getStorage() {
return storage;
}
public void setStorage(int storage) {
this.storage = storage;
}
//重写toString方法
public String toString() {
// TODO Auto-generated method stub
return bookId+"\t"+bookName+"\t"+price+"\t"+storage;
}
}
订单项类
import java.util.Date;
public class Order {
private long orderId;//订单编号
private double total;//订单总额
private Date date;//订单日期
private OrderItem[]items;
public Order() {
super();
}
public Order(long orderId, double total, Date date, OrderItem[] items) {
super();
this.orderId = orderId;
this.total = total;
this.date = date;
this.items = items;
}
public long getOrderId() {
return orderId;
}
public void setOrderId(long orderId) {
this.orderId = orderId;
}
public double getTotal() {
return total;
}
public void setTotal(double total) {
this.total = total;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public OrderItem[] getItems() {
return items;
}
public void setItems(OrderItem[] items) {
this.items = items;
}
}
订单类
public class OrderItem {
private String bookName;//图书名称
private double price;//图书单价
private int num;//购买数量
public OrderItem() {
super();
}
public OrderItem(String bookName, double price, int num) {
super();
this.bookName = bookName;
this.price = price;
this.num = num;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
//重写tostring方法
public String toString() {
return bookName+"\t"+num+"\t"+price;
}
}
图书系统
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
public class BookSys {
private Book[] books = new Book[5];
public BookSys(){
books[0]=new Book(1, "Java教程", 30.6, 30);
books[1]=new Book(2, "JSP指南", 42.57, 23);
books[2]=new Book(3, "SSH架构", 65.28, 15);
books[3]=new Book(45, "天山奇侠传",24, 10);
books[4]=new Book(203, "西游记", 80, 25);
}
public void showBooks() {
System.out.println("图书编号\t图书名称\t图书单价\t库存数量");
System.out.println("---------------------------------");
for (Book book : books) {
if(book!=null&&book.getStorage()!=0){
System.out.println(book);
}
}
System.out.println("---------------------------------");
}
//购书方法
public Order buyBook() {
OrderItem[] items = new OrderItem[10000];
double total = 0;
String input = "";
int i = 0, num = 0;
do {
Scanner sc = new Scanner(System.in);
System.out.println("请输入图书编号:");
String bookId = sc.next();
Book book = this.selectBook(books, bookId);// 调用图书编号检测方法
sc = new Scanner(System.in);
if (book != null) {
System.out.println("请输入购买数量:");
// 异常处理
try {
num = sc.nextInt();
} catch (Exception e) {
// TODO: handle exception
System.out.println("数量输入非法!");
sc = new Scanner(System.in);
input="y";
continue;// 结束本次循环并进入下一次循环。
}
// 判断库存量
if (num <= book.getStorage()) {
OrderItem item = new OrderItem(book.getBookName(),book.getPrice(), num);
// 检查书籍是否存在
OrderItem oi = this.checkBook(items, item);// 调用方法检查订单中是否已有同名书籍。
if (oi == null) {// 不存在添加
items[i] = item;
} else {// 存在更新数量
oi.setNum(oi.getNum() + item.getNum());
}
total += num * book.getPrice();// 计算总金额
book.setStorage((book.getStorage() - num));//库存更新
this.showBooks();
} else {
System.out.println("库存不足");
}
} else {
System.out.println("您输入的图书编号不存在!");
}
sc = new Scanner(System.in);
System.out.println("是否继续购书?(y/n)");
input = sc.next();
i++;
} while (input.equals("y"));
return new Order(System.currentTimeMillis(), total, new Date(), items);
}
// 订单显示方法
public void showOrder(Order order) {
if (order.getItems()[0] != null) {
System.out.println("\t图书订单");
System.out.println("订单号:" + order.getOrderId());
System.out.println("图书名称\t购买数量\t图书单价");
System.out.println("---------------------------");
// foreach 方法
for (OrderItem item : order.getItems()) {
if (item != null)
System.out.println(item);
}
System.out.println("---------------------------");
// 数字和日期的格式化:
DecimalFormat df = new DecimalFormat("0.00");
System.out.println("订单总额:" + df.format(order.getTotal()) + "元");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 hh:mm:ss");
System.out.println("订单时间:" + sdf.format(order.getDate()));
}
}
// 判断订单中是否存在书名相同的书,有则返回这本书,反之返回null。
public OrderItem checkBook(OrderItem[] items, OrderItem item) {
for (int i = 0; i < items.length; i++) {
if (items[i] != null
&& items[i].getBookName().equals(item.getBookName())) {
return items[i];
}
}
return null;
}
// 判断输入的图书编号是否存在,存在即返回此此图书对象,反之则返回null。
public Book selectBook(Book[] books, String bookId) {
try {
int id = Integer.parseInt(bookId);
for (int i = 0; i < books.length; i++) {
if(books[i].getStorage()==0){
books[i]=null;
}
if (books[i].getBookId() == id) {
return books[i];
}
}
} catch (Exception e) {
}
return null;
}
}
测试类
public class TestBook {
public static void main(String[] args) {
// TODO Auto-generated method stub
BookSys bs=new BookSys();
bs.showBooks();
Order order=bs.buyBook();
bs.showOrder(order);
}
}
Java集合框架
1,为什么使用集合框架
(1)存储的数量不确定,元素类型不确定。(int------->Integer,char----->Character)
(2)存储对应关系的数据
(3)高效存取,使用方便
2,集合的框架结构
(1)概念:是一套性能优良、使用方便的接口和实现类,位于java.util.*包。
(2)集合接口介绍
List:允许重复,有序
Set:不允许重复,无序
Map:存储键值对(key-value)
(3)Collection和Collecitons的区别:
Collection线性集合接口,旗下Set和List接口。
Collections是一个集合操作的工具类,实现了一些集合操作的算法(排序,遍历...)
(4)List接口的实现类
a,ArrayList:采用数组结构存储,遍历元素和随机访问的效率比较高
b,LinkedList:采用链表的存储结构,添加和删除元素时效率比较高
3,对象的比较:obj1 vs obj2
(1)java比较对象使用equals方法,默认equals和==是等价的。
(2)一般比较对象需要重写equals方法,定义规则。
(3)List集合的remove、contains方法,判断是否为同一对象的规则就是equals
(4)在HashSet、HashMap、HashTable中判断同一个的规则:equals+hasCode
4,对象的排序
Collections.sort(list); ---------->ClassCastException类转换异常
对象如果需要排序就必须实现Comparable接口,重写compareTo方法.
5,Set接口的实现类
(1)HashSet:元素乱序
(2)TreeSet:会对元素自动进行排序
6,集合的遍历工具:Iterator(迭代器)
Iterator itr=set.iterator();
while(itr.hasNext()){
Object o=itr.next();
System.out.println(o);
}
7,集合中的泛型的应用
(1)泛型就是为了限定元素的类型
(2)简化集合操作
(3)不足:只能存储泛型指定的类型
框架练习:
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
List list=new ArrayList();
User us1=new User();
us1.setName("张三");us1.setAge(12);us1.setAdress("延大创新");
list.add(us1);
list.add(new User("李四",12,"韦曲"));
list.add(new User("王五",13,"长安"));
list.add(new User("赵六",11,"小寨"));
list.add(new User("小王",14,"南门"));
//获取某个元素:根据下标
Object obj=list.get(1);
System.out.println(obj);
//集合大小
System.out.println(list.size());
//查找是否有此元素,返回布尔值
System.out.println(list.contains(us1));
//删掉此元素
list.remove(us1);
System.out.println(list);
//排序
Collections.sort(list);
System.out.println(list);
}
}
public class User implements Comparable{
private String name;
private int age;
private String address;
public User() {
super();
}
public User(String name) {
this.name = name;
}
public User(String name, int age) {
this.name = name;
this.age = age;
}
public User(String name, int age, String address) {
super();
this.name = name;
this.age = age;
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String toString() {
// TODO Auto-generated method stub
return name;
}
public boolean equals(Object obj) {
// TODO Auto-generated method stub
User other=(User)obj;
if(this.name.equals(other.getName()))
return true;
return false;
}
public int compareTo(Object o) {
// TODO Auto-generated method stub
User other=(User)o;
if(this.age>other.getAge()){
return -1;
}else if(this.age<other.getAge()){
return 1;
}
return 0;
}
}
user 类的测试类
public class Test2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
List list=new ArrayList();
list.add(new User("张三", 23));
list.add(new User("乌龟", 12));
list.add(new User("八戒", 77));
list.add(new User("悟空", 34));
System.out.println("排序前:"+list);
Collections.sort(list);
System.out.println("排序后:"+list);
}
}