java简单练习
1、购物车
package com.company.test01;
public class Test01 {
public static void main(String[] args) {
// 创建购物车
ShoppingCart cart = new ShoppingCart();
// 开始购物
Product p1 = new Product(1000, "iphone", 6000);
Product p2 = new Product(2000, "huawei", 5999);
Product p3 = new Product(3000, "sumaung", 5500);
Product p4 = new Product(4000, "xiaomi", 3999);
// 开始购物
cart.add(p1);
cart.add(p2,3);
cart.add(p3,2);
cart.add(p4,5);
cart.remove(p4,1);
// 打印详单
cart.print();
}
}
package com.company.test01;
// 超市中的商品
public class Product {
// Field
private int no;
private String name;
private double price;
// Constructor
public Product(){}
public Product(int no, String name, double price){
this.name = name;
this.no = no;
this.price = price;
}
// setter and getter
public void setNo(int no){
this.no = no;
}
public void setName(String name){
this.name = name;
}
public void setPrice(double price) {
this.price = price;
}
public int getNo(){
return no;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
// toString
public String toString(){
return "Public[编号:" + no + ",名称:" + name + ",价格:"+ price + "]";
}
// hashCode
// 商品编号的格式【1000~9999】
// 如果两个商品为1001 和 1002,则他们在同一个单向链表上
public int hasCode(){
return no/1000;
}
// equals
// 需求:如果商品名字和编码都一样表示是同一个商品
public boolean equals(Object o){
if(this ==o ) return true;
if(o instanceof Product){
Product p = (Product)o;
if(p.no == this.no && p.name.equals(this.name)){
return true;
}
}
return false;
}
}
package com.company.test01;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class ShoppingCart {
//使用Map存储商品条目
Map<Product, Integer> productMaps;
double totalPrice;
// Constructor
ShoppingCart(){
productMaps = new HashMap<Product, Integer>();
}
// 添加一个商品
public void add(Product p){
add(p,1);
}
// 添加N个商品
public void add(Product p, int n){
// 判断该购物车中是否含有该商品
if(!productMaps.containsKey(p)){
productMaps.put(p,n); // n会自动装箱
}else{
// 车中有该商品
int before = productMaps.get(p).intValue();
// intValue()将interger类型拆箱,当然由于自动拆箱可以省略不写
int after = before + n;
productMaps.put(p,after); // key重复,value覆盖
}
// 修改总价
totalPrice += p.getPrice()*n;
}
// 删除一个商品
public void remove(Product p){
remove(p,1);
}
// 删除N类商品
public void remove(Product p,int n){
if(!productMaps.containsKey(p) || productMaps.get(p)<n){
System.out.println("操作错误");
}else{
int before = productMaps.get(p);
int after = before - n;
// 如果商品数量和删除数量一致,需要删除条目
if(after == 0){
productMaps.remove(p);
}else{
productMaps.put(p, after);
}
// 修改总价
totalPrice -= p.getPrice()*n;
}
}
// 清空购物车
public void clear(){
productMaps.clear();
totalPrice = 0.0;
}
// 输出购物车详单
/*
格式:
购物详单:
10 苹果 10元
3 西瓜 30元
......
总价:40元
*/
public void print(){
StringBuffer sb = new StringBuffer();
sb.append("购物车详单:\n");
//遍历Map
Set<Product> key = productMaps.keySet();
Iterator<Product> it = key.iterator();
while (it.hasNext()){
Product k = it.next();
Integer v = productMaps.get(k);
sb.append("\t" + v.intValue() + "\t" + k + "\t" + v.intValue()*k.getPrice() + "\n");
}
sb.append("\t\t\t总价:" + totalPrice + "元");
System.out.println(sb);
}
}
2、拷贝目录下所有文件
package com.company.test02;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
/*
拷贝:d:/mydemo -> E:/mydemo
*/
public class Test {
public static void main(String[] args) {
File f = new File("d:/mydemo");
method(f);
}
public static void method(File f){
// f有可能是文件/目录
if(f.isFile()){
// 拷贝
String filePath = f.getAbsolutePath(); // 获取绝对路径
String newFilePath = "E" + filePath.substring(1);
File parentPath = new File(newFilePath).getParentFile();
if(!parentPath.exists()){
parentPath.mkdirs();
}
FileInputStream fis = null;
FileOutputStream fos = null;
// 为了保证关闭流,使用finally语句
try{
fis = new FileInputStream(filePath);
fos = new FileOutputStream(newFilePath);
// 复制
byte[] bytes = new byte[102400]; // 100KB
int temp = 0;
while((temp=fis.read(bytes)) != -1){
fos.write(bytes, 0, temp);
}
fos.flush();
}catch(Exception e){
e.printStackTrace();
}finally {
// 分别try...catch...
try{
if(fis!=null){
fis.close();
}
}catch (Exception e){
e.printStackTrace();
}
try{
if(fos!=null){
fos.close();
}
}catch (Exception e){
e.printStackTrace();
}
}
return;
}
// f是目录
File[] fs = f.listFiles(); // f文件下所有目录
for(File subF:fs){
System.out.println(subF.getAbsolutePath());
method(subF);
}
}
}
3、实现单链表
package com.company.test03;
/*
实现单链表Linked
*/
public class Linked {
// 成员内部类
class Node{
private String name;
private Node next;
public Node(String name){
this.name = name;
}
public void add(Node node){
if(this.next == null){
this.next = node;
}else{
this.next.add(node);
}
}
public void print(){
System.out.print(this.name + "==>");
if(this.next != null){
this.next.print();
}
}
public boolean search(String string){
if(this.name.equals(string)){
return true;
}else{
if(this.next != null){
return this.next.search(string);
}else{
return false;
}
}
}
public void delete(String string){
if(this.next.name.equals(string)){
this.next = this.next.next;
}else{
this.next.delete(string);
}
}
}
// 根节点
private Node root;
// 添加一个节点
public void add(String string){
Node node = new Node(string);
if(this.root == null){
this.root = node;
}else{
this.root.add(node);
}
}
// 打印节点
public void print(){
if(this.root != null){
this.root.print();
}
}
// 查找某个节点
public boolean search(String string){
if(this.root != null){
return this.root.search(string);
}else{
return false;
}
}
// 删除某个节点
public void delete(String string){
if(this.search(string)){
if(this.root.name.equals(string)){
if(this.root.next != null){
this.root = this.root.next;
}else{
this.root = null;
}
}else{
this.root.delete(string);
}
}
}
}
package com.company.test03;
public class LinkedTest {
public static void main(String[] args) {
Linked link = new Linked();
link.add("a");
link.add("b");
link.add("c");
link.add("d");
link.add("e");
link.add("f");
link.add("g");
link.print();
System.out.println();
System.out.println(link.search("a"));
link.delete("b");
link.delete("a");
link.print();
}
}
4、两个线程交替输出
两个线程对1个共享的数据操作
t1和t2两个线程对同一个num操作
t1输出1个,t1唤醒其他线程,t1等待
t2输出1个,t2唤醒其他线程,t2等待
package com.company.test03;
/*
需求:两个线程交替输出
两个线程对1个共享的数据操作
t1和t2两个线程对同一个num操作
t1输出1个,t1唤醒其他线程,t1等待
t2输出1个,t2唤醒其他线程,t2等待
*/
import java.lang.Exception;
public class Test {
public static void main(String[] args) throws Exception{
Num num = new Num(1);
Thread t1 = new Thread(new PrintOdd(num));
t1.setName("t1");
Thread t2 = new Thread(new PrintEven(num));
t2.setName("t2");
t1.start();
Thread.sleep(1000);
t2.start();
}
}
// 共享数据
class Num{
int count;
Num(int count){
this.count = count;
}
// 打印奇数的方法
/*
t1线程执行该方法,拿走num对象的对象锁
并且输出 t1--> xx,唤醒t2线程,虽然t2被唤醒
t2线程并不会马上执行,因为t2线程无法获取到对象锁。
当printOdd方法实现到 this.wait(),t1线程无期限等待
printOdd方法结束,释放对象锁,t2线程获取对象锁,开始执行printEven()方法。
*/
public synchronized void printOdd(){
System.out.println(Thread.currentThread().getName() + "-->" + (count++));
this.notifyAll(); // 唤醒该对象上所有线程
try{
Thread.sleep(1000);
this.wait(); // 让该线程无限等待
}catch(Exception e){
e.printStackTrace();
}
}
// 打印偶数的方法
public synchronized void printEven() throws Exception{
System.out.println(Thread.currentThread().getName() + "-->" + (count++));
this.notifyAll();
try{
Thread.sleep(1000);
this.wait(); // 让该线程无限等待
}catch(Exception e){
e.printStackTrace();
}
}
}
// 线程1
class PrintOdd implements Runnable{
Num num;
PrintOdd(Num num){
this.num = num;
}
public void run(){
while(true){
// 打印奇数
try{
num.printOdd();
}catch(Exception e){
e.printStackTrace();
}
}
}
}
// 线程2
class PrintEven implements Runnable{
Num num;
PrintEven(Num num){
this.num = num;
}
public void run(){
while(true){
// 打印偶数
try{
num.printEven();
}catch(Exception e){
e.printStackTrace();
}
}
}
}