版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報或認(rèn)領(lǐng)
文檔簡介
PAGEPAGE1《Java語言程序設(shè)計案例教程》習(xí)題參考答案習(xí)題一一、選擇題1、 C 2、B 3、B 4、A 5、D 6、C二、簡答題1、Java語言的特點(diǎn):Java2、(1)新建Java工程File->New->JavaProject(2)新建包 New->Package(3)新建類 New->Class(4)編寫源文件(5)運(yùn)行源文件3、publicclass test{publicstaticvoidmain(String[]args){System.out.println("這是****Java程序。");}}習(xí)題二一、選擇題1、D 2、A3、D 4、B 5、D 6、B 7、D 8、C 9、D 10、B 、B二、編程題1、publicstaticvoidmain(String[]args){Scannersc=newScanner(System.in);intnum=sc.nextInt();if(num%2==0){System.out.println(num+"是偶數(shù)");}else}}
System.out.println(num+"是奇數(shù)");2、publicstaticvoidmain(String[]args){System.out.println("請輸入全年應(yīng)納稅所得額");Scannersc=newScanner(System.in);doubletaxableIncome=sc.nextDouble();doubletax=0;if(taxableIncome<=36000){tax=taxableIncome*0.03;}elseif(taxableIncome<=144000){tax=taxableIncome*0.1-2520;}elseif(taxableIncome<=300000){tax=taxableIncome*0.2-16920;}elseif(taxableIncome<=420000){tax=taxableIncome*0.25-31920;}elseif(taxableIncome<=660000){tax=taxableIncome*0.3-52920;}elseif(taxableIncome<=960000){tax=taxableIncome*0.35-85920;}else{tax=taxableIncome*0.45-181920;}System.out.println("應(yīng)繳納個人所得稅稅額為:"+tax);}3、publicstaticvoidmain(String[]args){for(inti=100;i<=999;i++){intbai=i/100;intshi=i/10%10;intge=i%10;if(bai*bai*bai+shi*shi*shi+ge*ge*ge==i){System.out.println(i);}}}4、publicstaticvoidmain(String[]args){inti,j;for(i=1;i<10;i++){for(j=1;j<=i;j++){System.out.print(i+"x"+j+"="+i*j+""); }System.out.println();}}5、publicstaticvoidmain(String[]args){Scannerscan=newScanner(System.in);intn=scan.nextInt();Doublesum=0.0;//及格人數(shù)Doublesum2=0.0;//優(yōu)秀人數(shù)for(inti=0;i<n;i++){inta=scan.nextInt();if(a>=60){sum++;}//及格人數(shù)if(a>=85){sum2++;}//優(yōu)秀人數(shù)}System.out.print(Math.round(sum*100/n)+"%");System.out.print(Math.round(sum2*100/n)+"%");scan.close();}6、publicstaticvoidmain(String[]args){//方法一intcount=0;for(inti=1;i<=2020;i++){Strings=String.valueOf(i);if(s.contains("2")){//s2for(intj=0;j<s.length();j++){if(s.charAt(j)=='2'){count++;}}}}System.out.println(count);//方法二intcount=0;for(inti=1;i<=2020;++i){intt=i;while(t>0){if(t%10==2){count++;}t/=10;}}System.out.println(count);}習(xí)題三一、選擇題1、B 2、A3、A4、C 5、C 6、B 7、D 8、C9、D10、A、B12、B 13、A二、編程題1、publicclassRectangle{intlength;intwidth;publicRectangle(intlength,intwidth){this.length=length; this.width=width;}publicvoidgetcir(){intcir=2*(this.length+this.width);System.out.println("長方形的周長為:"+cir);}publicvoidgetArea(){intarea=this.length*this.width;System.out.println("長方形的面積為:"+area);}publicstaticvoidmain(String[]args){Rectangler=newRectangle(3,5);r.getArea(); r.getcir();}}2、publicclassFruit{Stringname;intnum;floatprice;publicFruit(Stringname,intnum,floatprice){=name;this.num=num;this.price=price;}publicstaticvoidmain(String[]args){Fruitapple=newFruit("apple",50,5.0f);Fruitpear=newFruit("pear",20,3.5f);FruitBanana=newFruit("banana",10,2.5f);System.out.println("蘋果的數(shù)量為:"+apple.num+";單價為:"+apple.price+"元");System.out.println("梨的數(shù)量為:"+pear.num+";單價為:"+pear.price+"元");System.out.println("香蕉的數(shù)量為:"+Banana.num+";單價為:"+Banana.price+"元");}}3、//學(xué)生類,封裝學(xué)生的學(xué)號、姓名、成績等信息。publicclassStu{StringstuID;StringstuName;floatscore;publicStu(Stringname,Stringid,floatscore){this.stuID=id;this.stuName=name;this.score=score;}}//主類publicclassmainTest{//打印輸出學(xué)生信息publicvoidprintout(Stus){System.out.println("學(xué)號為:"+s.stuID+";姓名為:"+s.stuName+";成績?yōu)椋?+s.score);}publicstaticvoidmain(String[]args){Stus=newStu("張三","001",90.0f);mainTestt=newmainTest();t.printout(s);}}4、//Employee父類publicclassEmployee{Stringname;floatbasic;Stringaddress;publicEmployee(Stringname,floatbasic,Stringaddress){=name;this.basic=basic;this.address=address;}publicvoidshow(){System.out.println("姓名為:"++";基本工資為:"+this.basic+";地址為:"+this.address);}}//Manager子類publicclassManagerextendsEmployee{Stringdepartment;publicManager(Stringname,floatbasic,Stringaddress,Stringdepartment){super(name,basic,address);this.department=department;}publicvoidshow(){System.out.println("姓名為:"++";基本工資為:"+this.basic+";地址為:"+this.address+";部門為:"+this.department);}publicstaticvoidmain(String[]args){Employeea=newManager("張三",2000.0f,"江蘇","研發(fā)");a.show();}}//Director子類publicclassDirectorextendsEmployee{Stringtransport;publicDirector(Stringname,floatbasic,Stringaddress,Stringtransport){super(name,basic,address);this.transport=transport;}publicvoidshow(){System.out.println("姓名為:"++";基本工資為:"+this.basic+";地址為:"+this.address+";交通工具為:"+this.transport);}publicstaticvoidmain(String[]args){Employeea=newDirector("李四",5000.0f,"江蘇","公交");a.show();}}5、//父類AdditionclassAddition{publicAddition(){}publicvoidadd(){System.out.println("父類Addition中的add()方法"); }}//NumberAddition類classNumberAdditionextendsAddition{publicvoidadd(){inta=5;intb=10;intc=a+b;System.out.println("NumberAddition類Addition中的add()方法:"+c);}}//TextConcatenation類classTextConcatenationextendsAddition{publicvoidadd(){Stringa="hello";Stringb="world";Stringc=a+b;System.out.println("TextConcatenation類Addition中的add()方法:"+c);}}//主類publicclassmainTest{publicstaticvoidmain(String[]args){NumberAdditionn=newNumberAddition();TextConcatenationt=newTextConcatenation();n.add();t.add();}}6、interfaceShape{voidgetArea();voidgetCir();}classRectangleimplementsShape{floatlength;floatwidth;publicRectangle(floatlength,floatwidth){this.length=length;this.width=width;}publicvoidgetArea(){System.out.println("矩形的面積為:"+this.length*this.width);}publicvoidgetCir(){ System.out.println("矩形的周長為:"+2*(this.length+this.width));}}publicclasst1{publicstaticvoidmain(String[]args){Rectangler=newRectangle(2.0f,1.5f);r.getArea();r.getCir();}}習(xí)題四一、選擇題1、C 2、B 3、C 4、D 5、B 6、D 7、C 8、A9、D 10、D二、編程題1、publicclassmainTest{//排序publicArrayList<String>Sort(ArrayList<String>a){inty=a.size();Stringstr1="";Stringstr2="";intflag;for(intx=0;x<a.size()-1;x++){for(inti=0;i<y-1;i++){str1=a.get(i);str2=a.get(i+1);flag=pareToIgnoreCase(str2);if(flag>=0){a.set(i,str2);a.set(i+1,str1);}}y=y-1;}returna;}publicstaticvoidmain(String[]args){ArrayList<String>a=newArrayList<String>(5);a.add("grape");a.add("orange");a.add("banana");a.add("apple");a.add("peach");mainTestt=newmainTest();ArrayList<String>b=t.Sort(a);for(intj=0;j<b.size();j++){System.out.println(b.get(j));}}}2.publicstaticvoidmain(String[]args){System.out.println("請輸入名字:");Scannersca=newScanner(System.in);Strings=sca.next();System.out.println("姓是:"+s.substring(0,1)+";名為"+s.substring(1));}3、importjava.util.ArrayList;//Cat類classCat{Stringname;publicCat(Stringname){=name;}publicvoidshow(){PAGEPAGE10System.out.println("name的值為:"+);}}//CatTest類publicclassCatTest{publicstaticvoidmain(String[]args){ArrayList<Cat>a=newArrayList<Cat>();a.add(newCat("cat1"));a.add(newCat("cat2"));a.add(newCat("cat3"));for(inti=0;i<a.size();i++){Catr=a.get(i);r.show();}}}4、importjava.util.HashMap;classBook{Stringtitle;publicBook(Stringtitle){this.title=title;}publicStringtoString(){returntitle;}}publicclassBookTest{publicstaticvoidmain(String[]args){HashMaphm=newHashMap();hm.put("001",newBook("Java程序設(shè)計"));hm.put("002",newBook("JSP應(yīng)用開發(fā)"));Bookb=(Book)hm.get("001");System.out.println("標(biāo)題為:"+b.toString());}}5、importjava.util.HashMap;importjava.util.Iterator;importjava.util.Set;publicclassStuTest{publicstaticvoidmain(String[]args){//創(chuàng)建HashMap對象hm,用put方法賦值HashMap<String,Integer>hm=newHashMap<String,Integer>();hm.put("張三",newInteger(98));hm.put("李四",newInteger(78));//打印學(xué)生成績Set<String>key=hm.keySet();Iterator<String>it=key.iterator();System.out.print("成績依次為:");while(it.hasNext()){System.out.print(hm.get(it.next())+" ");}//修改張三的成績hm.put("張三",newInteger(88));//打印學(xué)生成績key=hm.keySet();it=key.iterator();System.out.print("\n修改后的成績依次為:");while(it.hasNext()){System.out.print(hm.get(it.next())+" ");}}}6.importjava.util.Scanner;publicclassMain{publicstaticvoidmain(String[]args){Scannersc=newScanner(System.in);Strings=sc.nextLine();intmax=0;intindex=0;Stringa="abcdefghijklmnopqrstuvwxyz";intb[]=newint[26];for(inti=0;i<s.length();i++){b[a.indexOf(s.charAt(i))]++;}for(intj=0;j<b.length;j++){if(b[j]>max){max=b[j];index=j;}}System.out.println(a.substring(index,index+1));System.out.println(max);}}習(xí)題五一、選擇題1、C 2、C 3、B 4、A5、C 6、C二、編程題1、publicclassOutOfBound{publicstaticvoidmain(String[]args){int[]array={3,6,7,5,8,1,2,4,9,10};inti=0;try{System.out.println("元素的值為:"+array[i]);}catch(ArrayIndexOutOfBoundsExceptione){System.out.println("數(shù)組下標(biāo)越界了!");}}}2、classMyExceptionextendsException{privateStringcontent;//構(gòu)造方法publicMyException(Stringcontent){this.content=content;}//獲取異常描述信息publicStringgetContent(returncontent;}}publicclassTest{//檢查字符串元素是否都為小寫字母publicstaticvoidcheck(inti)throwsMyException{if(i<0)//MyException異常類對象thrownewMyException(i+"為負(fù)數(shù),不能做為數(shù)組長度!");}publicstaticvoidmain(Stringargs[]){//鍵盤輸入一個整數(shù)System.out.println("請輸入一個整數(shù):");Scannerscan=newScanner(System.in);intlen=scan.nextInt();len=len-20;try{//檢測數(shù)組長度的值check(len);}catch(MyExceptione){//處理異常System.out.println(e.getContent());}}}習(xí)題六一、選擇題1、A2、D 3、C 4、D 5、C二、編程題1、//取消按鈕事件privatevoidjButton2ActionPerformed(java.awt.event.ActionEventevt){System.exit(0);}//確定按鈕事件privatevoidjButton1ActionPerformed(java.awt.event.ActionEventevt){Stringname=jTextField1.getText();Stringpass=newString(jPasswordField1.getPassword());if(name.trim().equals("abc")&&pass.trim().equals("abc")){jLabel3.setText("驗證通過!");}elsejLabel3.setText("非法的用戶名或密碼!");}2、//斜體privatevoidjMenuItem4ActionPerformed(java.awt.event.ActionEventevt){jTextArea1.setFont(newFont(null,Font.ITALIC,12));}//藍(lán)色privatevoidjMenuItem3ActionPerformed(java.awt.event.ActionEventevt){jTextArea1.setForeground(Color.blue);}//綠色privatevoidjMenuItem2ActionPerformed(java.awt.event.ActionEventevt){jTextArea1.setForeground(Color.green);}//紅色privatevoidjMenuItem1ActionPerformed(java.awt.event.ActionEventevt){jTextArea1.setForeground(Color.red);}//退出privatevoidjMenuItem5ActionPerformed(java.awt.event.ActionEventevt){System.exit(-1);}習(xí)題七一、選擇題1、A 2、B 3、C 4、A 5、A二、編程題Statementcustomer的訪問并輸出。importjava.sql.Connection;importjava.sql.DriverManager;importjava.sql.ResultSet;importjava.sql.SQLException;importjava.sql.Statement;publicclassex1{publicstaticvoidmain(String[]args){try{//加載驅(qū)動Class.forName("com.mysql.jdbc.Driver");//建立連接Connectioncon=DriverManager.getConnection("jdbc:mysql://localhost:3306/dbstudent?characterEncoding=utf-8","root","123456");//實例化Statement對象Statement stmt=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);//執(zhí)行SQL語句Stringsql="select*fromcustomer";ResultSetrs=stmt.executeQuery(sql);//處理結(jié)果集while(rs.next()){System.out.println("讀者編號:"+rs.getInt("id")+"\t姓名:"+rs.getString("name")+"\t地址:"+rs.getString("address"));}//關(guān)閉連接if(rs !=null)rs.close();if(stmt!=null)stmt.close();if(conn!=null)conn.close();}catch(SQLExceptionex){System.out.println(ex.getMessage()+"路徑錯誤");}catch(ClassNotFoundExceptionex){System.out.println(ex.getMessage()+"驅(qū)動錯誤");}}}PreparedStatementCustomerIDimportjava.sql.Connection;importjava.sql.DriverManager;importjava.sql.PreparedStatement;importjava.sql.SQLException;publicclassex1{publicstaticvoidmain(String[]args){//定義sql語句Stringsql="deletefromcustomerwhereid=?";try{//加載驅(qū)動Class.forName("com.mysql.jdbc.Driver");//建立連接Connectioncon=DriverManager.getConnection("jdbc:mysql://localhost:3306/dbstudent?characterEncoding=utf-8","root","123456");//實例化PreparedStatement對象PreparedStatement ps=conn.prepareStatement(sql);//給參數(shù)賦值ps.setInt(1,1);//執(zhí)行SQL語句inti=ps.executeUpdate();//操作判斷if(i==1){System.out.println("記錄刪除成功!");}elseSystem.out.println("記錄刪除失??!");//關(guān)閉連接if(ps!=null)ps.close();if(conn!=null)conn.close();}catch(SQLExceptionex){ System.out.println(ex.getMessage路徑錯誤");}catch(ClassNotFoundExceptionex){ System.out.println(ex.getMessage驅(qū)動錯誤");}}}PreparedStatementCustomerID的記錄,并在控制臺輸出操作是否成功。importjava.sql.Connection;importjava.sql.DriverManager;importjava.sql.PreparedStatement;importjava.sql.SQLException;publicclassex1{publicstaticvoidmain(String[]args){//定義sql語句Stringsql="updatecustomersetname=?whereid=?";try{//加載驅(qū)動Class.forName("com.mysql.jdbc.Driver");//建立連接Connectioncon=DriverManager.getConnection("jdbc:mysql://localhost:3306/dbstudent?characterEncoding=utf-8","root","123456");//實例化PreparedStatement對象PreparedStatement ps=conn.prepareStatement(sql);//給參數(shù)賦值ps.setString(1,"kitty");ps.setInt(2,2);//執(zhí)行SQL語句inti=ps.executeUpdate();//操作判斷if(i==1){System.out.println("記錄更新成功!");}elseSystem.out.println("記錄更新失?。?);//關(guān)閉連接if(ps!=null)ps.close();if(conn!=null)conn.close();}catch(SQLExceptionex){ System.out.println(ex.getMessage路徑錯誤");}catch(ClassNotFoundExceptionex){ System.out.println(ex.getMessage驅(qū)動錯誤");}}}習(xí)題八一、選擇題1、B 2、D 3、A 4、C 5、C 6、D二、編程題1、JavaThreadRunnable接口。Threadrun()run()方法中編寫線程執(zhí)行的代newstart方法啟動線程。RunnableRunnablerun()方法,run()方法中編寫線程執(zhí)行的代碼,Thread構(gòu)造方法,以實現(xiàn)類的實例對象為參數(shù)創(chuàng)ThreadThreadstart()方法啟動線程。2、importjavax.swing.JFrame;importjavax.swing.JLabel;importjava.awt.BorderLayout;importjava.text.SimpleDateFormat;importjava.util.Date;publicclassTimeextendsJFrameimplementsRunnable{privateJLabeltimeLabel=null;privateDated=null;publicstaticvoidmain(Stringargs[]){newTime();}publicTime(){this.setTitle("多線程");this.setSize(400,300);this.setVisible(true);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);timeLabel=newJLabel();this.getContentPane().add(timeLabel,BorderLayout.NORTH);Threadt=newThread(this);t.start();}publicvoidrun(){while(true){d=newDate();SimpleDateFormatformat=new SimpleDateFormat("yyyy-MM-ddHH:mm:ss");Stringtime=format.format(d);timeLabel.setText("現(xiàn)在的時間是:"+time);}}}習(xí)題九一、選擇題1、D 2、A3、B 4、C 5、A6、B二、編程題1、importjava.io.BufferedReader;importjava.io.BufferedWriter;importjava.io.FileReader;importjava.io.FileWriter;importjava.io.IOException;publicclassTest{publicstaticvoidmain(Stringargs[]){BufferedReaderbr=null;BufferedWriterbw=null;try{
//根據(jù)字符流對象建立緩沖流對象bw=newBufferedWriter(newFileWriter("src/result.txt"));br=newBufferedReader(newFileReader("src/Stu.txt"));Stringstr=null;//初始化行號inti=1;//讀取數(shù)據(jù)while((str=br.readLine())!=null){bw.write(i+"");//寫入行號bw.write(str);bw.newLine();//寫入換行符i++;}bw.flush();//刷新緩沖輸入流}catch(IOExceptione){e.printStackTrace();}finally{try{//關(guān)閉緩沖流PAGEPAGE20bw.close();br.close();}catch(IOExceptione){e.printStackTrace();}}}}2、importjava.io.File;importjava.io.FileInputStream;importjava.io.FileOutputStream;importjava.io.IOException;publicclassTest{publicstaticvoidmain(Stringargs[]){try{Filef_in=newFile("src/fin.txt");//創(chuàng)建字節(jié)流對象FileOutputStreamfos=newFileOutputStream("src/fout.txt");FileInputStreamfis=newFileInputStream(f_in);for(inti=0;i<80;i++){fos.write(fis.read());}System.out.println("文件讀寫完成!");fos.close();fis.close();}catch(IOExceptione){System.out.println("文件讀寫異常!");}}}3、importjava.io.File;importjava.io.FileReader;importjava.io.FileWriter;importjava.io.IOException;publicclassTest{publicstaticvoidmain(Stringargs[]){try{Filef_in=newFile("src/fin.txt");//創(chuàng)建字節(jié)流對象FileWriterfw=newFileWriter("src/fout.txt");FileReaderfr=newFileReader(f_in);intstr;//初始化計數(shù)inti=0;//讀寫數(shù)據(jù)while((str=fr.read())!=-1){fw.write(str);i++;//換行if(i%40==0){fw.write("\n");}}fw.flush();//刷新緩沖輸入流System.out.println("文件讀寫完成!");fw.close();fr.close();}catch(IOExceptione){System.out.println("文件讀寫異常!");}}}習(xí)題十一、選擇題1、C 2、B 3、C 4、D 5、A 6、C二、編程題1、publicstaticvoidmain(String[]args){try{//根據(jù)域名得到IPInetAddressadd
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 工程施工合同詳細(xì)版
- 2025年阿壩貨運(yùn)運(yùn)輸駕駛員從業(yè)資格證考試試題
- 2025年煙臺經(jīng)營性道路客貨運(yùn)輸駕駛員從業(yè)資格考試
- 2025年隴南貨運(yùn)從業(yè)資格證在哪里練題
- 2025年淄博b2貨運(yùn)資格證全題
- 《高血壓治療新進(jìn)展》課件
- 第四單元 崇尚法治精神
- 水上救援車使用準(zhǔn)則
- 科研機(jī)構(gòu)鍋爐升級拆除合同
- 生物技術(shù)企業(yè)設(shè)計審查
- 足療培訓(xùn)課件
- 毛絨玩具行業(yè)創(chuàng)業(yè)計劃書
- 電力檢測項目計劃書
- 《簡易風(fēng)箏的制作》課件
- 體驗式家長會的實施與開展
- 《標(biāo)準(zhǔn)工時培訓(xùn)》課件
- 射擊館建設(shè)方案
- 應(yīng)用寫作-消息和通訊
- 華為公司客戶滿意度管理
- 四年級綜合實踐活動上三:學(xué)校中遵守規(guī)則情況調(diào)查教學(xué)課件
- 2023-2024學(xué)年江蘇省淮安市數(shù)學(xué)高一上期末復(fù)習(xí)檢測試題含解析
評論
0/150
提交評論