日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

Java面相对象练习案例其参考代码

發(fā)布時間:2023/12/14 java 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Java面相对象练习案例其参考代码 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

是自己在各種輔導書的課堂上作業(yè)上挑選的一些Java面向?qū)ο?/font>的相關(guān)習題。自己也跟著敲了好幾遍感覺非常的不錯,正在的學習的小伙伴可以用來聯(lián)系。(拍胸脯)保證非常的實用
對于創(chuàng)建對象及其調(diào)用,一些靜態(tài)代碼塊和的認識的學習非常有幫助,以案例的形式呈現(xiàn)出來。

習題目錄

    • 1.設(shè)計學生類并測試
    • 2. 設(shè)計學生類及子類并測試
    • 3. 設(shè)計Shape接口
    • 4.接口練習題
    • 5.超市購物程序
    • 6.銀行新用戶現(xiàn)金業(yè)務(wù)辦理
    • 7.USB接口程序設(shè)計
    • 8.模擬KTV點歌系統(tǒng)
    • 9.模擬新用戶注冊
    • 10.模擬斗地主游戲
    • 11.保存書店每日交易記錄程序設(shè)計

1.設(shè)計學生類并測試

請按照以下要求設(shè)計一個學生類Student,并進行測試。要求如下: (1)Student類中包含name、grade兩個屬性。 (2)給每個屬性定義兩個方法,一個方法用于設(shè)置值,另一個方法用于獲取值。
(3)Student類中定義一個無參的構(gòu)造方法和一個接收兩個參數(shù)的構(gòu)造方法,兩個參數(shù)分別為name、grade屬性賦值。
(4)在測試類中創(chuàng)建兩個Student對象,一個使用無參的構(gòu)造方法,然后調(diào)用設(shè)置值的方法給name、grade屬性賦值,另一個使用有參的構(gòu)造方法,在構(gòu)造方法中給name、grade屬性賦值。

輸入樣例: 結(jié)尾無空行 輸出樣例: 在這里給出相應(yīng)的輸出。例如: name=Tom,grade=92.0 name=Jack,grade=86.0 結(jié)尾無空行

實現(xiàn)代碼

class Main {public static void main(String[] args) { Student s1=new Student(); s1.setName("Tom"); s1.setGrade(92.0); Student s2=new Student("Jack",86.0); System.out.println("name="+s1.getName()+",grade="+s1.getGrade()); System.out.println("name="+s2.getName()+",grade="+s2.getGrade());} } class Student{private String name;private double grade;public Student() {}public Student(String name, double grade) {this.name = name;this.grade = grade;}public String getName() {return name;}public void setName(String name) {this.name = name;}public double getGrade() {return grade;}public void setGrade(double grade) {this.grade = grade;}}

2. 設(shè)計學生類及子類并測試

設(shè)計一個學生類Student和它的一個子類Undergraduate,要求如下:
(1)Student類有name和age屬性,一個包含兩個參數(shù)的構(gòu)造方法,用于給name和age屬性賦值,一個show()方法輸出Student的屬性信息。
(2)本科生類Undergraduate增加一個degree(學位)屬性。有一個包含三個參數(shù)的構(gòu)造方法,前兩個參數(shù)用于給繼承的name和age屬性賦值,第三個參數(shù)給degree賦值,一個show()方法用于輸出Undergraduate的屬性信息。
(3)在測試類中分別創(chuàng)建Student對象和Undergraduate對象,調(diào)用它們的show()。
輸出樣例:例如:

name: Tom age: 16
name: Jack age: 20 degree: bechalor (結(jié)尾無空行)

實現(xiàn)代碼

public class Student {private String name;private int age;public Student() {}public Student(String name, int age) {this.name = name;this.age = age;}public void show(){System.out.println("name: "+getName() +" age: "+getAge());}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 class Undergraduate extends Student{private String degree;public Undergraduate(String degree) {this.degree = degree;}public Undergraduate(String name, int age, String degree) {super(name, age);this.degree = degree;}public String getDegree() {return degree;}public void setDegree(String degree) {this.degree = degree;}@Overridepublic void show(){System.out.println("name: "+getName() +" age: "+getAge()+" degree: "+getDegree());} } public class Text {public static void main(String[] args) {Student s=new Student("Tom",16);Undergraduate un=new Undergraduate("Jack",20,"bechalor");s.show();un.show();} }

3. 設(shè)計Shape接口

設(shè)計一個Shape接口和它的兩個實現(xiàn)類Square和Circle。要求如下:
(1)Shape接口中有一個抽象方法area(),方法接收一個double類型的參數(shù),返回一個double類型的結(jié)果。
(2)Square和Circle中實現(xiàn)了Shape接口的area()抽象方法,分別求正方形和圓形的面積并返回。
在測試類中創(chuàng)建Square和Circle對象,計算邊長為2的正方形面積和半徑為3的圓形面積。 輸出樣例: square area:4.0
circle area:28.274333882308138 結(jié)尾無空行

實現(xiàn)代碼

public interface Shape { double area(double l); } public class Square implements Shape{@Overridepublic double area(double l) {double s;s=l*l;return s;} }public class Circle implements Shape{@Overridepublic double area(double l) {double s;s=Math.PI*l*l;return s;} } public class Test {public static void main(String[] args) {Shape s1= new Square();System.out.println("square area:"+s1.area(2));Shape circle=new Circle();System.out.println("circle area:"+circle.area(3));} }

4.接口練習題

設(shè)計一個PCI接口,一個實現(xiàn)類聲卡(SoundCard),和一個實現(xiàn)類網(wǎng)卡(NetWorkCard),設(shè)計一個主板類(MainBoard),一個裝配工(Assembler),要求如下
1.PCI接口有兩個抽象方法start()和stop()。
2.兩個實現(xiàn)類實現(xiàn)接口
3.主板類接受PCI類型的參數(shù)。調(diào)用傳入對象的方法。
4.裝配工創(chuàng)建聲卡,網(wǎng)卡,主板對象。

代碼如下

public interface PCI {void start();void stop(); } //聲卡 public class SoundCard implements PCI{@Overridepublic void start() {System.out.println("du du du du");}@Overridepublic void stop() {System.out.println("Sound Stop");} } //網(wǎng)卡 public class NetWorkCard implements PCI{@Overridepublic void start() {System.out.println("Send");}@Overridepublic void stop() {System.out.println("NetWork Stop");} } //主板 public class MainBoard {public void usePCICard(PCI pci){pci.start();pci.stop();}} //裝配工 public class Assembler {public static void main(String[] args){MainBoard mb=new MainBoard();NetWorkCard nw=new NetWorkCard();SoundCard sc=new SoundCard();mb.usePCICard(nw);mb.usePCICard(sc);} }

5.超市購物程序

編寫一個超市購物程序,實現(xiàn)超市購物功能。購物時,如果購物者所要購買的商品在超市中有,則提示購物者買到了某商品;如果超市中沒有購物者所需的商品,則提示購物者白跑了一趟,在超市中什么都沒有買到要求如下
1.定義商品類Product,封裝姓名屬性proName。
2.定義超市類,聲明超市名稱marketName和存放商品的倉庫proArr,定義一個賣出指定商品的方法sell(),該方法遍歷倉庫,如果有該商品,返回商品名,否則返回null。
3.定義購物者類Person,聲明姓名name屬性,編寫購物shopping()方法。
4.定義測試類Shopping,創(chuàng)建商品和超市對象,存入貨物。創(chuàng)建購物者,進行購物。

在這里插入代碼片public class Product {public Product() {}public Product(String proName) {this.proName = proName;}private String proName;public String getProName() {return proName;}public void setProName(String proName) {this.proName = proName;} }public class Market {public Market(String marketName) {this.marketName = marketName;}private String marketName;private Product[] proArr;public String getMarketName() {return marketName;}public void setMarketName(String marketName) {this.marketName = marketName;}public Product[] getProArr() {return proArr;}public void setProArr(Product[] proArr) {this.proArr = proArr;}public Product sell(String name){for (int i = 0; i < proArr.length; i++) {if(proArr[i].getProName()==name){return proArr[i];}}return null;} }public class Person {public Person() {}public Person(String name) {this.name = name;}private String name;public String getName() {return name;}public void setName(String name) {this.name = name;}Product shopping(Market market,String name){return market.sell(name);} }

6.銀行新用戶現(xiàn)金業(yè)務(wù)辦理

編寫一個銀行新用戶現(xiàn)金業(yè)務(wù)辦理程序,使其模擬新用戶到銀行辦理現(xiàn)金存取業(yè)務(wù)時的場景。要求此場景中,要模擬出銀行對用戶到來的歡迎動作、對用戶離開的提醒動作,以及用戶的開戶、存款和取款動作,在完成開戶、存款和取款操作后,要提示用戶的賬戶余額。具體要求如下
1.定義一個銀行類Bank,①定義銀行的名稱bankName、用戶的名稱 name、密碼password、賬戶余額balance和交易金額tuenover。②定義歡迎方法welcome()和歡迎下次再來welcomeNext()方法。③用構(gòu)造方法進行開戶操作,開戶時需扣除10元卡費④定義存款deposit()和取款withdrawal()方法,取款時要驗證密碼和取款金額是否大于賬戶余額。
2.編寫交易類Trade,在此類中模擬新用戶去銀行辦理現(xiàn)金業(yè)務(wù)的場景。

public class Bank {public static String bankName;private String name ;private String password;private double balance;private double tuenover;public Bank(String name, String password, double tuenover) {this.name = name;this.password = password;this.balance = tuenover-10;this.tuenover = tuenover;}static void welcome(){System.out.println("歡迎來到"+bankName);}public void deposit(double tuenover){balance+=tuenover;System.out.println("您此次存款"+balance+"元,您的余額為"+tuenover+"元。");}public void withdrawal(String password,double tuenover){if(this.password.equals(password)){if(balance>=tuenover){balance-=tuenover;System.out.println("您此次取款"+balance+"元,您的余額為"+tuenover+"元。");}else {System.out.println("對不起,賬戶余額不足");}}else{System.out.println("對不起,密碼錯誤");}}static void welcomeNext(){System.out.println("歡迎再來"+bankName);} }public class Trade {public static void main(String[] args) {Bank.bankName="崽崽銀行";Bank.welcome();Bank bank=new Bank("小崽","123456",300);bank.withdrawal("12345",500);bank.withdrawal("123456",500);bank.deposit(500);bank.withdrawal("123456",500);Bank.welcomeNext();} }

7.USB接口程序設(shè)計

此任務(wù)中涉及到的對象有USB接口、鼠標、鍵盤、麥克風以及計算機。要實現(xiàn)此程序,就需要對這些對象進行相應(yīng)的編寫。要求如下
1.設(shè)計一個USB接口,定義啟動turnOn()和停止turnOff()的方法。 2.寫接口的實現(xiàn)類鼠標Mouse、鍵盤KeyBoard和麥克風Mic,在實現(xiàn)類中要實現(xiàn)這些設(shè)備的啟動和關(guān)閉方法。 3.由于這些設(shè)備是在計算機中使用的,所以接下來編寫一個計算機類。類中編寫一個USB插槽usbArr和安裝USB設(shè)備add()的方法。同時定義開機powerOn()和關(guān)機powerOff()的方法。
4.編寫測試類,實例化計算機對象,并向計算機對象中添加三個USB設(shè)備,運行查看結(jié)果。

public interface USB {void turnOn();void turnOff(); } public class Mouse implements USB{@Overridepublic void turnOn() {System.out.println("鼠標啟動了");}@Overridepublic void turnOff() {System.out.println("鼠標關(guān)閉了");} } public class KeyBoard implements USB{@Overridepublic void turnOn() {System.out.println("鍵盤開啟了");}@Overridepublic void turnOff() {System.out.println("鍵盤關(guān)閉了");} } public class Mic implements USB{@Overridepublic void turnOn() {System.out.println("麥克風開啟了");}@Overridepublic void turnOff() {System.out.println("麥克風關(guān)閉了");} } public class Computer {private USB[]usbArr=new USB[4];public void add(USB usb){for (int i = 0; i < usbArr.length; i++) {if(usbArr[i]==null){usbArr[i]=usb;break;}}}public void powerOn(){System.out.println("電腦開機la");for (int i = 0; i < usbArr.length; i++) {if(usbArr[i]!=null)usbArr[i].turnOn();}}public void powerOff(){for (int i = 0; i < usbArr.length; i++) {if(usbArr[i]!=null)usbArr[i].turnOff();}System.out.println("電腦關(guān)機la");} } public class Text {public static void main(String[] args) {Computer c=new Computer();Mouse mouse=new Mouse();KeyBoard keyBoard=new KeyBoard();Mic mic=new Mic();c.add(mouse);c.add(keyBoard);c.add(mic);c.powerOn();c.powerOff();} }

8.模擬KTV點歌系統(tǒng)

分別使用Linkeduist和AravList集合,實現(xiàn)編寫一個模擬KTV點歌系統(tǒng)的程序。在程序中,指令0代表添加歌曲,指令1代表將所選歌曲置頂,指令2代表將所選歌曲提前一位,指令3名退出該系統(tǒng)。要求根據(jù)用戶輸入的指令和歌曲名展現(xiàn)歌曲列表。

public class Text {public static void main(String[] args) {System.out.println("歡迎來到點歌系統(tǒng)");System.out.println("0:添加歌曲");System.out.println("1:將所選歌曲置頂");System.out.println("2:將所選歌曲提前一位");System.out.println("3:退出該系統(tǒng)");LinkedList linkedList=new LinkedList();addMusicList(linkedList);while (true){System.out.println("輸入你想執(zhí)行的序號");int command=new Scanner(System.in).nextInt();switch(command){case 0:addMusic(linkedList);break;case 1:setTop(linkedList);break;case 2:setbefore(linkedList);break;case 3:exit();break;}}}private static void addMusicList(LinkedList linkedList){linkedList.add("夜的第七章");linkedList.add("稻香");linkedList.add("霍元甲");linkedList.add("青花瓷");linkedList.add("菊花臺");System.out.println("原始歌曲列表為"+linkedList);}private static void addMusic(LinkedList linkedList){System.out.println("請您輸入要添加的曲目");String song=new Scanner(System.in).next();linkedList.add(song);System.out.println(song+"添加完成");}private static void setTop(LinkedList linkedList){System.out.println("請您輸入要置頂?shù)那?#34;);String song=new Scanner(System.in).next();int index= linkedList.indexOf(song);if(index<0){System.out.println("該曲目不存在");}else{linkedList.remove(index);linkedList.addFirst(song);}}private static void setbefore(LinkedList linkedList){System.out.println("請您輸入要前置的曲目");String song=new Scanner(System.in).next();int index= linkedList.indexOf(song);if(index<0){System.out.println("該曲目不存在");} else if(index==0){System.out.println("該歌曲已經(jīng)在第一個");}else{linkedList.remove(index);linkedList.add(index-1,song);}}private static void exit(){System.out.println("即將退出系統(tǒng)");System.exit(0);} } public class KTVByArrayList {public static void main(String[] args) {System.out.println("歡迎來到點歌系統(tǒng)");System.out.println("0:添加歌曲");System.out.println("1:將所選歌曲置頂");System.out.println("2:將所選歌曲提前一位");System.out.println("3:退出該系統(tǒng)");ArrayList arrayList=new ArrayList();addMusicList(arrayList);while(true){System.out.println("輸入你想執(zhí)行的序號");int command=new Scanner(System.in).nextInt();switch(command){case 0:addMusic(arrayList);break;case 1:setTop(arrayList);break;case 2:setbefore(arrayList);break;case 3:exit();break;}}}private static void addMusicList(ArrayList arrayList){arrayList.add("夜的第七章");arrayList.add("稻香");arrayList.add("霍元甲");arrayList.add("青花瓷");arrayList.add("菊花臺");System.out.println("原始歌曲列表為"+arrayList);}private static void addMusic(ArrayList arrayList){System.out.println("請您輸入要添加的曲目");String song=new Scanner(System.in).next();arrayList.add(song);System.out.println(song+"添加完成");}private static void setTop(ArrayList arrayList){System.out.println("請您輸入要置頂?shù)那?#34;);String song=new Scanner(System.in).next();int index= arrayList.indexOf(song);if(index<0){System.out.println("該曲目不存在");}else{arrayList.remove(index);arrayList.add(0,song);}}private static void setbefore(ArrayList arrayList){System.out.println("請您輸入要前置的曲目");String song=new Scanner(System.in).next();int index= arrayList.indexOf(song);if(index<0){System.out.println("該曲目不存在");} else if(index==0){System.out.println("該歌曲已經(jīng)在第一個");}else{arrayList.remove(index);arrayList.add(index-1,song);}}private static void exit(){System.out.println("即將退出系統(tǒng)");System.exit(0);}}

9.模擬新用戶注冊

編寫一個模擬新浪微博用戶注冊的程序,要求使用HashSet
集合實現(xiàn)。假設(shè)當用戶輸入用戶名、密碼、確認密碼、生日(輸入格式為yyy-mm-dd為正確)手機號碼(手機號長度為11位,并且以13、15、17或18為開頭的手機號位為正確人郵箱(包含符號“@”為正確)信息之后,判斷信息輸入是否正確,正確驗證用戶是否重復(fù)注冊,如果不是重復(fù)注冊則注冊成功。要求如下
1.創(chuàng)建一個用戶類包含用戶名userName,密碼passwor,手機號telNumber,郵箱email,生日birthday,在類中重寫其中的HashCodel()equls0方法。
2.創(chuàng)建一個用戶注冊類來模擬注冊信息,該類中可以用HashSet集合來創(chuàng)建一個數(shù)據(jù)列表, 然后向列表中添加兩條初始用戶信息。
3.創(chuàng)建一個校驗信息類,在類中實現(xiàn)校驗用戶輸入信息的方法。
注:校驗信息類中的正則表達式為本人所寫,非原題標準答案,如有錯誤,望指正。

public class User {private String userName;private String password ;private String telNumber;private String email;private Date birthday;public User(String userName, String password, String telNumber, String email, Date birthday) {this.userName = userName;this.password = password;this.telNumber = telNumber;this.email = email;this.birthday = birthday;}@Overridepublic boolean equals(Object o) {if (this == o) return true;if (o == null || getClass() != o.getClass()) return false;User user = (User) o;return userName.equals(user.userName);}@Overridepublic int hashCode() {return Objects.hash(userName);} } public class CheckInfo {public static HashSet<User> USER_DATA =new HashSet<>();public CheckInfo(HashSet<User> USER_DATA) {this.USER_DATA=USER_DATA;}public String checkAction(String userName, String password,String repassword , String telNumber,String email,String birthday){StringBuffer result=new StringBuffer();int state=1;if (!password.equals(repassword)){result.append("兩次密碼不一致,");state=2;}if(birthday.matches("\\d{4}-\\d{2}-\\d{2}")){}else{result.append("生日格式不正確,");state=2;}if(telNumber.matches("1[3,5,7,8]\\d{9}")){}else{result.append("手機格式不正確,");state=2;}if(email.matches("\\w{1,30}@[a-zA-Z0-9]{1,30}\\.([a-zA-Z0-9]{1,30}){1,2}")){}else{result.append("郵箱格式不正確,");state=2;}if(state==1){DateFormat foemat=new SimpleDateFormat("yyyy-mm-dd");Date datebirthday=null;try {datebirthday=foemat.parse(birthday);} catch (ParseException e) {e.printStackTrace();}User newUser=new User(userName,repassword , telNumber,email,datebirthday);if(!USER_DATA.add(newUser)){result.append("用戶重復(fù)");state=2;}if(state==1){result.append("注冊成功!");}}return result.toString();}} public class UserRegister {public static HashSet<User> USER_DATA =new HashSet<>();public static void main(String[] args) {initDate();Scanner sc =new Scanner(System.in);System.out.println("請輸入用戶名");String userName=sc.nextLine();System.out.println("請輸入密碼");String password=sc.nextLine();System.out.println("請再次輸入密碼");String repassword=sc.nextLine();System.out.println("請輸入電話號碼");String telNumber=sc.nextLine();System.out.println("請輸入電子郵件");String email=sc.nextLine();System.out.println("請輸入生日");String birthday=sc.nextLine();CheckInfo checkInfo=new CheckInfo(USER_DATA);String result=checkInfo.checkAction(userName,password,repassword,telNumber,email,birthday);System.out.println("注冊結(jié)果"+result);}public static void initDate(){User user=new User("林黛玉","ldy,123","18123457697","lindaiyu@itcase",new Date());User user2=new User("薛寶釵","xbc,123","18123856797","xuebaochai@itcase",new Date());USER_DATA.add(user);USER_DATA.add(user2);}}

10.模擬斗地主游戲

編寫一個斗地主洗牌發(fā)牌的程序,要求按照斗地主的規(guī)則完成洗牌發(fā)牌的過程。總共有54張牌,牌面由花色和數(shù)字(包括J、Q、K、
A字母)組成,花色有?、?、?和?這4種,小🃏表示小王,大🃏表示大王。將這54張牌打亂順序,共有3位玩家參與游戲,每人輪流一次摸一-張牌,剩余3張留為底牌。程序結(jié)束,打印每人手中的紙牌和底牌。

public class Text {public static void main(String[] args) {//準備花色?、?、?和?ArrayList<String> color = new ArrayList<>();color.add("?");color.add("?");color.add("?");color.add("?");//準備數(shù)字ArrayList<String> number = new ArrayList<>();for (int i = 2; i <= 10; i++) {number.add(i + "");}number.add("J");number.add("Q");number.add("K");number.add("A");HashMap<Integer, String> map = new HashMap<>();int index = 0;for (String thiscolor : color) {for (String thisnumber : number) {map.put(index++, thiscolor + thisnumber);}}map.put(index++, "小🃏");map.put(index++, "大🃏");ArrayList<Integer> cards = new ArrayList<>();for (int i = 0; i < 54; i++) {cards.add(i);}Collections.shuffle(cards);ArrayList<Integer> player1 = new ArrayList<>();ArrayList<Integer> player2 = new ArrayList<>();ArrayList<Integer> player3 = new ArrayList<>();ArrayList<Integer> iSceretCards = new ArrayList<>();for (int i = 0; i < cards.size(); i++) {if (i >= 51) {iSceretCards.add(i);} else if (i % 3 == 0) {player1.add(i);} else if (i % 3 == 1) {player2.add(i);} else {player3.add(i);}}Collections.sort(player1);Collections.sort(player2);Collections.sort(player3);ArrayList<String> sPlayer1 = new ArrayList<>();ArrayList<String> sPlayer2 = new ArrayList<>();ArrayList<String> sPlayer3 = new ArrayList<>();ArrayList<String> sSeretCards = new ArrayList<>();for (Integer key : player1) {sPlayer1.add(map.get(key));}for (Integer key : player2) {sPlayer2.add(map.get(key));}for (Integer key : player3) {sPlayer3.add(map.get(key));}for (Integer key : iSceretCards) {sSeretCards.add(map.get(key));}System.out.println("玩家1"+sPlayer1);System.out.println("玩家2"+sPlayer2);System.out.println("玩家3"+sPlayer3);System.out.println("底牌"+sSeretCards);} }

11.保存書店每日交易記錄程序設(shè)計

編寫一個保存書店每日交易記錄的程序,使用字節(jié)流將書店的交易信息記錄在本地的CSV文件中。當用戶輸入圖書編號時,后臺會根據(jù)圖書編號查詢到相應(yīng)圖書信息,并返回打印出來。用戶緊接著輸入購買數(shù)量,系統(tǒng)會判斷庫存是否充足,如果充足則將信息保存至本地的CSV文件中,其中,每條信息包含了“圖書編號”“圖書名稱”“購買數(shù)量”“單價”“總價”“出版社”等數(shù)據(jù),每個數(shù)據(jù)之間用英文逗號或空格分割,每條數(shù)據(jù)之間由換行符分割。保存的時候需要判斷本地是否存在當天的數(shù)據(jù),如果存在則追加,不存在則新建。(本題有一定的難度,慎重書寫)

public class Books {int id;String name;double price;int number;double money;String Publish;public Books(int id,String name, double peice, int number, double money, String publish) {this.id=id;this.name = name;this.price = peice;this.number = number;this.money = money;Publish = publish;}@Overridepublic String toString() {return "Books{" +"圖書編號:" + id + '\'' +",圖書名稱:" + name + '\'' +",圖書價格 :" + price +", 圖書數(shù)量:" + number +", 單價" + money +", 庫存數(shù)量" + Publish + '\'' +'}';}public void setNumber(int number) {this.number = number;} } public class RecordBooksOrder {static ArrayList<Books> bookslist=new ArrayList<>();public static void main(String[] args) {init();for (Books books : bookslist) {System.out.println(books);}Scanner sc=new Scanner(System.in);while(true){System.out.println("請輸入圖書編號");int bookId=sc.nextInt();Books stockBooks=getbooksById(bookId);if(stockBooks!=null){System.out.println("當前圖書信息"+stockBooks);System.out.println("請輸入購買數(shù)量");int bookNumber=sc.nextInt();if(bookNumber<=stockBooks.number){Books books=new Books(stockBooks.id,stockBooks.name,stockBooks.price, (stockBooks.number-bookNumber),stockBooks.money,stockBooks.Publish);FileUtil.saveBooks(books);}else{System.out.println("庫存不足");}}else{System.out.println("圖書編號輸入錯誤");}}}public static void init(){Books goods1=new Books(101,"Java基礎(chǔ)入門",44.50,100,4450.00,"清華大學出版社");Books goods2=new Books(102 ,"Java編程思想",108.00,50,5400.00,"機械工業(yè)出版社");Books goods3=new Books(102,"瘋狂Java講義",99.00,100,9900.00,"電子工業(yè)出版社");bookslist.add(goods1);bookslist.add(goods2);bookslist.add(goods3);}public static Books getbooksById(int bookId){for (int i = 0; i < bookslist.size(); i++) {Books thisBooks=bookslist.get(i);if(bookId==thisBooks.id)return thisBooks;}return null;} } public class FileUtil {public static final String SEPARATE_FIELD=",";public static final String SEPARATE_LINE="\r\n";public static void saveBooks(Books books){Date date=new Date();DateFormat format =new SimpleDateFormat("yyyyMMdd");String name="銷售記錄"+format.format(date)+".csv";InputStream in=null;try {in=new FileInputStream(name);if(in!=null){in.close();createFile(name,true,books);}} catch (FileNotFoundException e) {createFile(name,false,books);}catch (IOException e) {e.printStackTrace();}}private static void createFile(String name, boolean label, Books books) {BufferedOutputStream out=null;StringBuffer sbf=new StringBuffer();try {if(label) {out = new BufferedOutputStream(new FileOutputStream(name, true));}else{out = new BufferedOutputStream(new FileOutputStream(name));String[] fieldSort=new String[]{"圖書編號","圖書名稱","購買數(shù)量","單價","總價","出版社"};for(String filedKey:fieldSort){sbf.append(filedKey).append(SEPARATE_FIELD);}}sbf.append(SEPARATE_FIELD);sbf.append(books.id).append(SEPARATE_FIELD);sbf.append(books.name).append(SEPARATE_FIELD);sbf.append(books.number).append(SEPARATE_FIELD);sbf.append((double)books.price).append(SEPARATE_FIELD);sbf.append((double)books.money).append(SEPARATE_FIELD);sbf.append(books.Publish).append(SEPARATE_FIELD);String str=sbf.toString();byte[] b=str.getBytes();for (int i = 0; i < b.length; i++) {out.write(b[i]);}} catch (Exception e) {e.printStackTrace();}finally {try {out.close();} catch (IOException e) {e.printStackTrace();}}}}

總結(jié)

以上是生活随笔為你收集整理的Java面相对象练习案例其参考代码的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。