JAVA 皮常德2-7章答案
- 格式:doc
- 大小:117.00 KB
- 文档页数:20
Java程序设计各章习题及其答案第一章习题及思考题1、Java程序是由什么组成的?一个程序中必须有public类吗?Java源文件的命名规则是怎样的?答:一个Java源程序是由若干个类组成。
一个Java程序不一定需要有public类:如果源文件中有多个类时,则只能有一个类是public 类;如果源文件中只有一个类,则不将该类写成public也将默认它为主类。
源文件命名时要求源文件主名应与主类(即用public修饰的类)的类名相同,扩展名为.java。
如果没有定义public类,则可以任何一个类名为主文件名,当然这是不主张的,因为它将无法进行被继承使用。
另外,对Applet小应用程序来说,其主类必须为public,否则虽然在一些编译编译平台下可以通过(在BlueJ下无法通过)但运行时无法显示结果。
2、怎样区分应用程序和小应用程序?应用程序的主类和小应用程序的主类必须用public修饰吗?答:Java Application是完整的程序,需要独立的解释器来解释运行;而Java Applet则是嵌在HTML编写的Web页面中的非独立运行程序,由Web浏览器内部包含的Java解释器来解释运行。
在源程序代码中两者的主要区别是:任何一个Java Application 应用程序必须有且只有一个main方法,它是整个程序的入口方法;任何一个Applet小应用程序要求程序中有且必须有一个类是系统类Applet的子类,即该类头部分以extends Applet结尾。
应用程序的主类当源文件中只有一个类时不必用public修饰,但当有多于一个类时则主类必须用public修饰。
小应用程序的主类在任何时候都需要用public来修饰。
3、开发与运行Java程序需要经过哪些主要步骤和过程?答:主要有三个步骤(1)、用文字编辑器notepad(或在Jcreator,Gel, BuleJ,Eclipse, Jbuilder等)编写源文件;(2)、使用Java编译器(如Javac.exe)将.java源文件编译成字节码文件.class;(3)、运行Java程序:对应用程序应通过Java解释器(如java.exe)来运行,而对小应用程序应通过支持Java标准的浏览器(如Microsoft Explorer)来解释运行。
public class xiti9{public static void main(String args[]) {int x=4;int y;if(x<1){y=x;}else if(x>=10){y=4*x;}else{y=3*x-2;}System.out.println("y="+y);}}习题12public class xiti12{public static void main(String args[]) {int sum=0;for(int k=1;k<=10;k++){sum=sum+k*k;}System.out.println("sum="+sum); }}习题13public class xiti13{public static void main(String args[]) {intt,a=3,b=5,c=8;if(a<b){t=a;a=b;b=t;}if(a<c){t=a;a=c;c=t;}{t=b;b=c;c=t;}System.out.println("大小顺序输出为:"+a+" "+b+" "+c); }}习题14public class xiti14{public static void main(String args[]){int n=1;System.out.print("\n1-100之间的所有素数为:\n"+" 3"); for(int i=1;i<=100;i++){for(int j=2;j<=i/2;j++){if(i%j==0){break;}if(j==i/2){System.out.print(" "+i);n++;}}}System.out.println("\n共有"+n+"个素数。
//******************************************************************** // AverageOfThree.java Author: Lewis/Loftus//// Solution to Programming Project 2.2//******************************************************************** import java.util.Scanner;public class AverageOfThree{//----------------------------------------------------------------- // Reads three integers from the user and prints their average.//----------------------------------------------------------------- public static void main (String[] args){int num1, num2, num3;double average;Scanner scan = new Scanner (System.in);System.out.print ("Enter the first number: ");num1 = scan.nextInt();System.out.print ("Enter the second number: ");num2 = scan.nextInt();System.out.print ("Enter the third number: ");num3 = scan.nextInt();average = (double) (num1+num2+num3) / 3;System.out.println ("The average is: " + average);}}//******************************************************************** // AverageOfThree2.java Author: Lewis/Loftus//// Alternate solution to Programming Project 2.2//******************************************************************** import java.util.Scanner;public class AverageOfThree2{//----------------------------------------------------------------- // Reads three integers from the user and prints their average.//----------------------------------------------------------------- public static void main (String[] args){int num1, num2, num3;double average;Scanner scan = new Scanner (System.in);System.out.print ("Enter three numbers: ");num1 = scan.nextInt();num2 = scan.nextInt();num3 = scan.nextInt();average = (double) (num1+num2+num3) / 3;System.out.println ("The average is: " + average);}}//******************************************************************** // Balloons.java Author: Lewis/Loftus//// Solution to Programming Project 2.17//********************************************************************import javax.swing.JApplet;import java.awt.*;public class Balloons extends JApplet{//----------------------------------------------------------------- // Draws a set of balloons on strings.//----------------------------------------------------------------- public void paint (Graphics page){setBackground (Color.white);// draw the stringspage.setColor (Color.black);page.drawLine (45, 95, 100, 300);page.drawLine (90, 100, 100, 300);page.drawLine (60, 100, 100, 300);page.drawLine (122, 85, 100, 300);page.drawLine (145, 115, 100, 300);// draw the balloonspage.setColor (Color.blue);page.fillOval (20, 30, 50, 65);page.setColor (Color.yellow);page.fillOval (70, 40, 40, 60);page.setColor (Color.red);page.fillOval (40, 50, 40, 55);page.setColor (Color.green);page.fillOval (100, 30, 45, 55);page.setColor (Color.cyan);page.fillOval (120, 55, 50, 60);}}//******************************************************************** // BigDipper.java Author: Lewis/Loftus//// Solution to Programming Project 2.16//********************************************************************import javax.swing.JApplet;import java.awt.*;public class BigDipper extends JApplet{//----------------------------------------------------------------- // Draws the Big Dipper constellation and some other stars.//----------------------------------------------------------------- public void paint (Graphics page){setBackground (Color.black);page.setColor (Color.white);page.drawLine (100, 80, 110, 120);page.drawLine (110, 120, 165, 115);page.drawLine (165, 115, 175, 70);page.drawLine (100, 80, 175, 70);page.drawLine (175, 70, 245, 20);page.drawLine (245, 20, 280, 30);// Draw some extra starspage.fillOval (50, 50, 4, 4);page.fillOval (70, 150, 3, 3);page.fillOval (90, 30, 3, 3);page.fillOval (220, 140, 4, 4);page.fillOval (280, 170, 3, 3);page.fillOval (310, 100, 4, 4);page.fillOval (360, 20, 3, 3);}}//******************************************************************** // BusinessCard.java Author: Lewis/Loftus//// Solution to Programming Project 2.20//********************************************************************import javax.swing.JApplet;import java.awt.*;public class BusinessCard extends JApplet{//----------------------------------------------------------------- // Draws a business card.//----------------------------------------------------------------- public void paint (Graphics page){setBackground (Color.yellow);page.setColor (Color.red);page.fillOval (10, 20, 60, 60);page.setColor (Color.cyan);page.fillRect (25, 35, 130, 25);page.setColor (Color.black);page.drawString ("James C. Kerplunk", 35, 50);page.drawString ("President and CEO", 85, 80);page.drawString ("Origin Software, Inc.", 85, 100);page.drawLine (225, 20, 225, 80);page.drawLine (195, 50, 255, 50);page.setColor (Color.blue);page.drawString ("where it all begins...", 115, 135);}}//******************************************************************** // ChangeCounter.java Author: Lewis/Loftus//// Solution to Programming Project 2.10//******************************************************************** import java.util.Scanner;public class ChangeCounter{//----------------------------------------------------------------- // Computes the total value of a collection of coins.//----------------------------------------------------------------- public static void main (String[] args){int quarters, dimes, nickels, pennies;int total, dollars, cents;Scanner scan = new Scanner(System.in);System.out.print ("Enter the number of quarters: ");quarters = scan.nextInt();System.out.print ("Enter the number of dimes: ");dimes = scan.nextInt();System.out.print ("Enter the number of nickels: ");nickels = scan.nextInt();System.out.print ("Enter the number of pennies: ");pennies = scan.nextInt();total = quarters * 25 + dimes * 10 + nickels * 5 + pennies;dollars = total / 100;cents = total % 100;System.out.println ("Total value: " + dollars + " dollars and " + cents + " cents.");}}//******************************************************************** // DrawName.java Author: Lewis/Loftus//// Solution to Programming Project 2.15//********************************************************************import javax.swing.JApplet;import java.awt.*;public class DrawName extends JApplet{//----------------------------------------------------------------- // Draws a name.//----------------------------------------------------------------- public void paint (Graphics page){setBackground (Color.cyan);page.setColor (Color.black);page.drawString ("John A. Lewis", 50, 50);}}//******************************************************************** // FloatCalculations.java Author: Lewis/Loftus//// Solution to Programming Project 2.4//******************************************************************** import java.util.Scanner;public class FloatCalculations{//----------------------------------------------------------------- // Reads two floating point numbers and prints their sum,// difference, and product.//----------------------------------------------------------------- public static void main (String[] args){float num1, num2;Scanner scan = new Scanner (System.in);System.out.print ("Enter the first number: ");num1 = scan.nextFloat();System.out.print ("Enter the second number: ");num2 = scan.nextFloat();System.out.println ("Their sum is: " + (num1+num2));System.out.println ("Their difference is: " + (num1-num2));System.out.println ("Their product is: " + (num1*num2));}}//******************************************************************** // Fraction.java Author: Lewis/Loftus//// Solution to Programming Project 2.13//******************************************************************** import java.util.Scanner;public class Fraction{//----------------------------------------------------------------- // Computes the floating point equivalent of a fraction.//----------------------------------------------------------------- public static void main (String[] args){int numerator, denominator;float value;Scanner scan = new Scanner(System.in);System.out.print ("Enter the numerator: ");numerator = scan.nextInt();System.out.print ("Enter the denominator: ");denominator = scan.nextInt();value = (float) numerator / denominator;System.out.println ("Floating point equivalent: " + value);}}//******************************************************************** // HousePicture.java Author: Lewis/Loftus//// Solution to Programming Project 2.19//********************************************************************import javax.swing.JApplet;import java.awt.*;public class HousePicture extends JApplet{//----------------------------------------------------------------- // Draws a house scene.//----------------------------------------------------------------- public void paint (Graphics page){setBackground (Color.cyan);page.setColor (Color.gray);page.fillRect (0, 200, 400, 50); // groundpage.setColor (Color.blue);page.fillRect (50, 125, 300, 100); // housepage.setColor (Color.green);page.fillRect (180, 175, 40, 50); // doorpage.setColor (Color.yellow);page.fillRect (100, 155, 40, 25); // windowpage.fillRect (260, 155, 40, 25); // windowpage.setColor (Color.black);page.fillRect (40, 100, 320, 40); // roofpage.fillOval (210, 200, 6, 6); // doorknobpage.setColor (Color.red);page.fillRect (80, 80, 20, 40); // chimneypage.setColor (Color.darkGray);page.fillOval (80, 60, 20, 20); // smokepage.fillOval (85, 50, 15, 25); // smokepage.fillOval (90, 45, 15, 20); // smokepage.setColor (Color.white);page.fillOval (200, 30, 80, 40); // cloudpage.fillOval (230, 40, 80, 40); // cloud}}//******************************************************************** // InfoParagraph.java Author: Lewis/Loftus//// Solution to Programming Project 2.3//********************************************************************import java.util.Scanner;public class InfoParagraph{//----------------------------------------------------------------- // Reads information about a person and incorporates it into an// output paragraph.//----------------------------------------------------------------- public static void main (String[] args){String name, age, college, pet;Scanner scan = new Scanner (System.in);System.out.print ("What is your name? ");name = scan.nextLine();System.out.print ("How old are you? ");age = scan.nextLine();System.out.print ("What college do you attend? ");college = scan.nextLine();System.out.print ("What is your pet's name? ");pet = scan.nextLine();System.out.println ();System.out.print ("Hello, my name is " + name + " and I am ");System.out.print (age + " years\nold. I'm enjoying my time at "); System.out.print (college + ", though\nI miss my pet " + pet);System.out.println (" very much!");System.out.println ();}}//******************************************************************** // Lincoln4.java Author: Lewis/Loftus//// Solution to Programming Project 2.1//********************************************************************public class Lincoln4{//----------------------------------------------------------------- // Prints a quote from Abraham Lincoln, including quotation// marks.//----------------------------------------------------------------- public static void main (String[] args){System.out.println ("A quote by Abraham Lincoln:");System.out.println ("\"Whatever you are, be a good one.\"");}}//******************************************************************** // MilesToKilometers.java Author: Lewis/Loftus//// Solution to Programming Project 2.6//******************************************************************** import java.util.Scanner;public class MilesToKilometers{//----------------------------------------------------------------- // Converts miles into kilometers. The value for miles is read// from the user.//----------------------------------------------------------------- public static void main (String[] args){final double MILES_PER_KILOMETER = 1.60935;double miles, kilometers;Scanner scan = new Scanner(System.in);System.out.print ("Enter the distance in miles: ");miles = scan.nextDouble();kilometers = MILES_PER_KILOMETER * miles;System.out.println ("That distance in kilometers is: " +kilometers);}}//******************************************************************** // MoneyConversion.java Author: Lewis/Loftus//// Solution to Programming Project 2.11//******************************************************************** import java.util.Scanner;public class MoneyConversion{//----------------------------------------------------------------- // Reads a monetary amount and computes the equivalent in bills// and coins.//----------------------------------------------------------------- public static void main (String[] args){double total;int tens, fives, ones, quarters, dimes, nickels;int remainingCents;Scanner scan = new Scanner(System.in);System.out.print ("Enter monetary amount: ");total = scan.nextDouble();remainingCents = (int) (total * 100);tens = remainingCents / 1000;remainingCents %= 1000;fives = remainingCents / 500;remainingCents %= 500;ones = remainingCents / 100;remainingCents %= 100;quarters = remainingCents / 25;remainingCents %= 25;dimes = remainingCents / 10;remainingCents %= 10;nickels = remainingCents / 5;remainingCents %= 5;System.out.println ("That's equivalent to:");System.out.println (tens + " ten dollar bills");System.out.println (fives + " five dollar bills");System.out.println (ones + " one dollar bills");System.out.println (quarters + " quarters");System.out.println (dimes + " dimes");System.out.println (nickels + " nickels");System.out.println (remainingCents + " pennies");}}//******************************************************************** // OlympicRings.java Author: Lewis/Loftus//// Solution to Programming Project 2.18//********************************************************************import javax.swing.JApplet;import java.awt.*;public class OlympicRings extends JApplet{//----------------------------------------------------------------- // Draws the olympic logo.//----------------------------------------------------------------- public void paint (Graphics page){final int DIAMETER = 50;setBackground (Color.lightGray);page.setColor (Color.blue);page.drawOval (30, 40, DIAMETER, DIAMETER);page.setColor (Color.yellow);page.drawOval (60, 70, DIAMETER, DIAMETER);page.setColor (Color.black);page.drawOval (90, 40, DIAMETER, DIAMETER);page.setColor (Color.green);page.drawOval (120, 70, DIAMETER, DIAMETER);page.setColor (Color.red);page.drawOval (150, 40, DIAMETER, DIAMETER);}}//******************************************************************** // PieChart.java Author: Lewis/Loftus//// Solution to Programming Project 2.22//******************************************************************** import javax.swing.JApplet;import java.awt.*;public class PieChart extends JApplet{//----------------------------------------------------------------- // Draws the pie chart with equal sections.//----------------------------------------------------------------- public void paint (Graphics page){setBackground (Color.lightGray);page.setColor (Color.blue);page.fillArc (70, 25, 100, 100, 0, 45);page.setColor (Color.yellow);page.fillArc (70, 25, 100, 100, 45, 45);page.setColor (Color.black);page.fillArc (70, 25, 100, 100, 90, 45);page.setColor (Color.green);page.fillArc (70, 25, 100, 100, 135, 45);page.setColor (Color.red);page.fillArc (70, 25, 100, 100, 180, 45);page.setColor (Color.magenta);page.fillArc (70, 25, 100, 100, 225, 45);page.setColor (Color.cyan);page.fillArc (70, 25, 100, 100, 270, 45);page.setColor (Color.orange);page.fillArc (70, 25, 100, 100, 315, 45);}}//******************************************************************** // Seconds.java Author: Lewis/Loftus//// Solution to Programming Project 2.8//******************************************************************** import java.util.Scanner;public class Seconds{//----------------------------------------------------------------- // Computes the total number of seconds for a given number of// hours, minutes, and seconds.//-----------------------------------------------------------------public static void main (String[] args){final int SECONDS_PER_HOUR = 3600;final int SECONDS_PER_MINUTE = 60;int seconds, minutes, hours, totalSeconds;Scanner scan = new Scanner(System.in);System.out.print ("Enter the number of hours: ");hours = scan.nextInt();System.out.print ("Enter the number of minutes: ");minutes = scan.nextInt();System.out.print ("Enter the number of seconds: ");seconds = scan.nextInt();totalSeconds = hours * SECONDS_PER_HOUR +minutes * SECONDS_PER_MINUTE +seconds;System.out.println ();System.out.println ("Total seconds: " + totalSeconds);}}//******************************************************************** // Seconds2.java Author: Lewis/Loftus//// Solution to Programming Project 2.9//******************************************************************** import java.util.Scanner;public class Seconds2{//----------------------------------------------------------------- // Computes the number of hours, minutes, and seconds that are// equivalent to the number of seconds entered by the user.//----------------------------------------------------------------- public static void main (String[] args){final int SECONDS_PER_HOUR = 3600;final int SECONDS_PER_MINUTE = 60;int seconds, minutes, hours;Scanner scan = new Scanner(System.in);System.out.print ("Enter the number of seconds: ");seconds = scan.nextInt();hours = seconds / SECONDS_PER_HOUR;seconds = seconds % SECONDS_PER_HOUR; // remaining secondsminutes = seconds / SECONDS_PER_MINUTE;seconds = seconds % SECONDS_PER_MINUTE; // remaining secondsSystem.out.println ();System.out.println ("Hours: " + hours);System.out.println ("Minutes: " + minutes);System.out.println ("Seconds: " + seconds);}}//******************************************************************** // ShadowName.java Author: Lewis/Loftus//// Solution to Programming Project 2.21//********************************************************************import javax.swing.JApplet;import java.awt.*;public class ShadowName extends JApplet{//----------------------------------------------------------------- // Draws a name with a slightly offset shadow.//----------------------------------------------------------------- public void paint (Graphics page){setBackground (Color.yellow);page.setColor (Color.black);page.drawString ("John A. Lewis", 50, 50);page.setColor (Color.red);page.drawString ("John A. Lewis", 49, 49);}}//******************************************************************** // Snowman2.java Author: Lewis/Loftus//// Solution to Programming Project 2.14//********************************************************************import javax.swing.JApplet;import java.awt.*;public class Snowman2 extends JApplet{//----------------------------------------------------------------- // Draws a snowman with added features.//----------------------------------------------------------------- public void paint (Graphics page){final int MID = 130;final int TOP = 50;setBackground (Color.cyan);page.setColor (Color.blue);page.fillRect (0, 175, 300, 50); // groundpage.setColor (Color.yellow);page.fillOval (260, -40, 80, 80); // sunpage.setColor (Color.white);page.fillOval (MID-20, TOP, 40, 40); // headpage.fillOval (MID-35, TOP+35, 70, 50); // upper torsopage.fillOval (MID-50, TOP+80, 100, 60); // lower torsopage.setColor (Color.red);page.fillOval (MID-3, TOP+50, 6, 6); // buttonpage.fillOval (MID-3, TOP+60, 6, 6); // buttonpage.setColor (Color.black);page.fillOval (MID-10, TOP+10, 5, 5); // left eyepage.fillOval (MID+5, TOP+10, 5, 5); // right eyepage.drawArc (MID-10, TOP+20, 20, 10, 10, 160); // frownpage.drawLine (MID-25, TOP+60, MID-50, TOP+40); // left armpage.drawLine (MID+25, TOP+60, MID+55, TOP+60); // right armpage.drawLine (MID-20, TOP+5, MID+20, TOP+5); // brim of hatpage.fillRect (MID-15, TOP-20, 30, 25); // top of hatpage.drawString ("John Lewis", 20, 20); // artist}}//******************************************************************** // SquareCalculations.java Author: Lewis/Loftus//// Solution to Programming Project 2.12//******************************************************************** import java.util.Scanner;public class SquareCalculations{//----------------------------------------------------------------- // Computes a square's perimeter and area given the length of// one side.//----------------------------------------------------------------- public static void main (String[] args){int side, perimeter, area;Scanner scan = new Scanner(System.in);System.out.print ("Enter the length of a square's side: ");side = scan.nextInt();perimeter = side * 4;area = side * side;System.out.println ("Perimeter: " + perimeter);System.out.println ("Area: " + area);}}//********************************************************************// TempConverter2.java Author: Lewis/Loftus//// Solution to Programming Project 2.5//******************************************************************** import java.util.Scanner;public class TempConverter2{//----------------------------------------------------------------- // Computes the Celsius equivalent of a Fahrenheit value read// from the user. Uses the formula C = (5/9)(F - 32).//----------------------------------------------------------------- public static void main (String[] args){final int BASE = 32;final double CONVERSION_FACTOR = 5.0 / 9.0;double celsiusTemp, fahrenheitTemp;Scanner scan = new Scanner(System.in);System.out.print ("Enter a Fahrenheit temperature: ");fahrenheitTemp = scan.nextDouble();celsiusTemp = CONVERSION_FACTOR * (fahrenheitTemp - BASE);System.out.println ("Celsius Equivalent: " + celsiusTemp);}}//******************************************************************** // TravelTime.java Author: Lewis/Loftus//// Solution to Programming Project 2.7//******************************************************************** import java.util.Scanner;public class TravelTime{//----------------------------------------------------------------- // Converts miles into kilometers. The value for miles is read// from the user.//-----------------------------------------------------------------public static void main (String[] args){int speed, distance;double time;Scanner scan = new Scanner(System.in);System.out.print ("Enter the speed: ");speed = scan.nextInt();System.out.print ("Enter the distance traveled: ");distance = scan.nextInt();time = (double) distance / speed;System.out.println ("Time elapsed during trip: " + time); }}。
二1.角谷猜想:任何一个正整数n,如果它是偶数则除以二,如果是奇数则乘以3再加上1,这样得到一个新的整数,如此继续进行上述处理,则最后得到的数一定是1,编写应用程序和小程序分别验证:3~10000之间任何正整数都满足上述规则。
2.编写一个程序模拟同时掷2个骰子。
程序要用Math.random( )模拟产生第一个骰子,然后再产生第二个骰子,将2个结果相加。
和等于7的可能性最大,等于2和12的可能性最小。
下图表示了出现36种情况组合。
程序模拟掷3600次骰子,判断求和结果是否合理,共有6种情况的和是7,故在3600次掷骰子的结果中应当有1/6的可能性是7。
123456 1234567 2345678 3456789 45678910 567891011 6789101112一、实验步骤:1.应用程序:package cp2;public class a4 {public static void main(String[] args) {boolean a=true;int j;for(int i=3;i<=10000;i++){for(j=i;j>1;){if(j%2==0){j=j/2;}else{j=j*3+1;}}if(j!=1){a=false;break;}}System.out.println(a);}}运行结果:true小程序:package cp2;import java.awt.*;import java.applet.*;public class a5 extends Applet{Label lab1;TextField input1;int num1=1;public void init(){lab1=new Label("任意输入3~10000的一个整数");input1=new TextField(10);add(lab1);add(input1);}public boolean action(Event e,Object o){num1=Integer.parseInt(input1.getText());showStatus("");input1.setText("");repaint();showStatus("这个数是"+num1);return true;}public void paint(Graphics g){int xpos=50,ypos=50,i=0;int xpos1=xpos;while(num1!=1){if(num1%2==0){num1=num1/2;g.drawString(Integer.toString(num1), xpos, ypos);}else{num1=num1*3+1;g.drawString(Integer.toString(num1), xpos, ypos);}xpos=xpos+50;i++;if(i%5==0){ypos=ypos+10;xpos=xpos1;}}}}运行结果:2.程序:package cp2;import java.awt.*;import java.applet.*;public class a6 extends Applet{Label lab;TextField input;int a,b,t2,t3,t4,t5,t6,t7,t8,t9,t10,t11,t12;double i2,i3,i4,i5,i6,i7,i8,i9,i10,i11,i12;public void init(){lab=new Label("输入次数");input=new TextField(10);add(lab);add(input);}public boolean action(Event e,Object o){int time=Integer.parseInt(input.getText()); showStatus("");input.setText("");showStatus("模拟次数"+time);t2=t3=t4=t5=t6=t7=t8=t9=t10=t11=t12=0;for(int i=1;i<=time;i++){a=(int)(Math.random()*6+1);b=(int)(Math.random()*6+1);switch(a+b){case 12:t12++;break;case 11:t11++;break;case 10:t10++;break;case 9:t9++;break;case 8:t8++;break;case 7:t7++;break;case 6:t6++;break;case 5:t5++;break;case 4:t4++;break;case 3:t3++;break;case 2:t2++;break;}i12=(double)t12/i;i11=(double)t11/i;i10=(double)t10/i;i9=(double)t9/i;i8=(double)t8/i;i7=(double)t7/i;i6=(double)t6/i;i5=(double)t5/i;i4=(double)t4/i;i3=(double)t3/i;i2=(double)t2/i;repaint();}//repaint();return true;}public void paint(Graphics g){g.drawString("各种和的概率:",25,40);g.drawString("12:"+i12,25,55);g.drawString("11:"+i11,25,70);g.drawString("10:"+i10,25,85);g.drawString("9:"+i9,25,100);g.drawString("8:"+i8,25,115);g.drawString("7:"+i7,25,130);g.drawString("6:"+i6,25,145);g.drawString("5:"+i5,25,160);g.drawString("4:"+i4,25,175);g.drawString("3:"+i3,25,190);g.drawString("2:"+i2,25,205);}}运行结果:三一、实验内容:1.采用循环语句打印如下图形:* *** ***** ******* ****2.编写一个applet,采用公式:e x=1+x1/1!+x2/2!+……..+x n/n!.三、实验步骤:1.程序:package cp3;import java.awt.*;import java.applet.*;public class a1 extends Applet{Label lab;TextField input;int a,b[]=new int[20],i,j;public void init(){lab=new Label("输入数字");input=new TextField(10);add(lab);add(input);}public boolean action(Event e,Object o){a=Integer.parseInt(input.getText());input.setText("");repaint();return true;}public void paint(Graphics g){for(int i=0;a!=0;i++){b[i]=a%10;a/=10;}for(j=0;b[j]!=0;j++);for(int t=--j;t>=0;t--){g.drawString(Integer.toString(b[t]),j*20-t*20,55); }for(i=0;i<b.length;i++){b[i]=0;}}}运行结果:* *** ***** ******* ********* *****2:程序:package cp3;import java.awt.*;import java.applet.*;public class a6 extends Applet{Label lab1,lab2;TextField input1,input2;int a,b,i;double sum=0;public class aa{int mult(int n){int s=1;for(int j=1;j<=n;j++)s*=j;return s;}}public void init(){lab1=new Label("输入x大小");input1=new TextField(10);lab2=new Label("输入n值");input2=new TextField(10);add(lab1);add(input1);add(lab2);add(input2);}public boolean action(Event e,Object o){a=Integer.parseInt(input1.getText()); b=Integer.parseInt(input2.getText()); input1.setText("");input2.setText("");showStatus("");sum=0;aa c=new aa();for(i=0;i<=b;i++){sum+=(double)(Math.pow(a,i))/(double)c.mult(i);}showStatus("结果为"+sum);return true;}}输入x=1,n=30时的运行结果:四二、实验内容:1.定义一个类,它包含了一个int类型的变量x、若干个构造函数(根据你的需要)和一个输出方法show( )。
Java2 实用教程(第三版)课后习题参考答案第1 章Java 入门1. 开发与运行Jav a 程序需要经过哪些主要步骤和过程?答:( 1)编写Java 源文件:使用文本编辑器(Edit 或记事本),拓展名为.java(2)编译Java 源文件:使用Java 编译器(javac.exe)。
得到字节码文件*.class(3)运行Java 程序:Java 应用程序使用Java 解释器(java.exe)执行字节码文件;Java 小应用程序使用支持Java 标准的浏览器来执行。
2. 怎样区分应用程序和小应用程序?应用程序的主类或小应用程序的主类必须用public 修饰吗?答:①应用程序必须有main 方法,这个方法是程序执行的入口。
小应用程序没有main 方法。
②应用程序的主类不一定用public 修饰;小应用程序的主类必须用public 修饰。
3. Jav a 程序是由什么组成的?一个程序中必须要有public 类吗?Jav a 源文件的命名规则是怎样的?答:①Java 程序由类组成。
②应用程序可以没有public 类;小应用程序一定有一个类是public 类(主类)。
③应用程序:如果只有一个类,源文件名与该类的类名相同,拓展名为.java;有多个类时,如果有public 类(最多一个),源文件名与public 类的类名相同,拓展名是.java;没有public 类,源文件名与任何一个类的类名相同即可,拓展名为.java。
小应用程序:源文件名与主类的类名相同,拓展名是.java。
4. 在运行小程序的HTM L 文件中可以使用codebas e 属性指定小程序的字节码所驻留的目录。
如果不使用codebas e 属性,小程序的字节码文件必须和运行它的HTM L 文件在同一目录中。
编写一个小程序并将小程序的字节码存放在某个目录中,比如C:\5000;把运行该小程序的HTM L 文件(注意其中的codebas e 属性):<applet code=你的小程序的字节码width=200 height=300 codebase=C: \5000></applet>存放在另一个目录中。
第2章习题2-5、计算一个人一段时期的薪水,第1天1分钱,第2天2分钱,每天翻倍。
要求用户输入天数(输入检验),列表显示每天的薪水,及薪水总和(输出人民币的单位:“元”)。
#include<iostream>using namespace std;void main(){int daynum;float daypay, paysum=0;do{cout<<"请输入天数(>1整数):";cin>>daynum;}while(daynum<=1); //有效性检验for(int i=1; i<=daynum; i++){ daypay=i/100.0;cout<<"第"<<i<<"天薪水:"<<daypay <<"元\t";if(i%2==0)cout<<endl;paysum+=daypay; //列表输出每天薪水,计算总薪水}cout<<endl;cout<<"薪水总和:"<<paysum<<"元"; //输出总薪水}2-7、用for循环计算1/30+2/29+3/28+…+30/1。
#include<iostream>using namespace std;void main(){int i;float sum=0;for(i=1;i<=30;i++)sum+=i/float(31-i);cout<<"sum="<<sum;}2-8、用循环语句输出如下图形。
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA#include<iostream>using namespace std;void main(){int i,j,k;for(i=0;i<=3;i++) //控制行{ for(j=0;j<i;j++)cout<<' '; //控制每行输出的' '的数目for(k=7-i;k>i;k--) //控制每行输出的'A'的数目cout<<'A';cout<<endl;}for(i=1;i<=3;i++){ for(j=3;j>i;j--)cout<<' '; //控制每行输出的' '的数目for(k=0;k<2*i+1;k++) //控制每行输出的'A'的数目cout<<'A';cout<<endl;}}2-9、采用循环结构计算公式s的前30项和。
习题解答习题一(第1章)1.2.需3个步骤:1) 用文本编辑器编写源文件。
2) 使用编译源文件,得到字节码文件。
3) 使用解释器运行程序。
3. :\\\\;.;4. B5. 源文件的扩展名是,字节码的扩展名是。
6.D 。
习题二(第2章)1.2. { ( b) {;}( b) {;}}{() {("老师好");}}{( []) {();((12,236));((234,120));();();}}3.如果源文件中有多个类,但没有类,那么源文件的名字只要和某个类的名字相同,并且扩展名是就可以了,如果有一个类是类,那么源文件的名字必须与这个类的名字完全相同,扩展名是。
4.行尾风格。
习题三(第3章)1.用来标识类名、变量名、方法名、类型名、数组名、文件名的有效字符序列称为标识符。
标识符由字母、下划线、美元符号和数字组成,第一个字符不能是数字。
不是标识符。
2.关键字就是语言中已经被赋予特定意义的一些单词,不可以把关键字作为名字来用。
不是关键字。
3.,,,,,,,。
4.属于操作题,解答略。
5.属于操作题,解答略。
6. E {( [ ]) {'A''Z';( <)(" ");}}7.不可以。
习题四(第4章)1.110。
不规范。
2.新亲亲斤!!。
3.{( ) {(913112) {("是三等奖");}(20959627) {("是二等奖");}(87531659) {("是一等奖");{("未中奖");}}}4.;{( []) {();= 0; 存放电量= 0; 用户需要交纳的电费("输入电量:");();( <= 90 >=1){= *0.6计算的值}( <= 150 >=91){= 90*0.6+(90)*1.1计算的值}(>150){= 90*0.6+(150-90)*1.1+(150)*1.7计算的值}{("输入电量:""不合理");}("电费5.2f");}}5. E {( [ ]) {'A''Z';( <)("%2c");();( <)("%2c",(32));}}6. 5 {( []) {0;(1<=1000) {(0);}()("完数:");}}}7E {( []) {111;0;() {1;(1<){*i;};(>9876);;}("满足条件的最大整数:"+(1));}}习题五(第5章)1.用类创建对象时。
二1.角谷猜想:任何一个正整数n,如果它是偶数则除以二,如果是奇数则乘以3再加上1,这样得到一个新的整数,如此继续进行上述处理,则最后得到的数一定是1,编写应用程序和小程序分别验证:3~10000之间任何正整数都满足上述规则。
2.编写一个程序模拟同时掷2个骰子。
程序要用Math.random( )模拟产生第一个骰子,然后再产生第二个骰子,将2个结果相加。
和等于7的可能性最大,等于2和12的可能性最小。
下图表示了出现36种情况组合。
程序模拟掷3600次骰子,判断求和结果是否合理,共有6种情况的和是7,故在3600次掷骰子的结果中应当有1/6的可能性是7。
123456 1234567 2345678 3456789 45678910 567891011 6789101112一、实验步骤:1.应用程序:package cp2;public class a4 {public static void main(String[] args) {boolean a=true;int j;for(int i=3;i<=10000;i++){for(j=i;j>1;){if(j%2==0){j=j/2;}else{j=j*3+1;}}if(j!=1){a=false;break;}}System.out.println(a);}}运行结果:true小程序:package cp2;import java.awt.*;import java.applet.*;public class a5 extends Applet{Label lab1;TextField input1;int num1=1;public void init(){lab1=new Label("任意输入3~10000的一个整数");input1=new TextField(10);add(lab1);add(input1);}public boolean action(Event e,Object o){num1=Integer.parseInt(input1.getText());showStatus("");input1.setText("");repaint();showStatus("这个数是"+num1);return true;}public void paint(Graphics g){int xpos=50,ypos=50,i=0;int xpos1=xpos;while(num1!=1){if(num1%2==0){num1=num1/2;g.drawString(Integer.toString(num1), xpos, ypos);}else{num1=num1*3+1;g.drawString(Integer.toString(num1), xpos, ypos);}xpos=xpos+50;i++;if(i%5==0){ypos=ypos+10;xpos=xpos1;}}}}运行结果:2.程序:package cp2;import java.awt.*;import java.applet.*;public class a6 extends Applet{Label lab;TextField input;int a,b,t2,t3,t4,t5,t6,t7,t8,t9,t10,t11,t12;double i2,i3,i4,i5,i6,i7,i8,i9,i10,i11,i12;public void init(){lab=new Label("输入次数");input=new TextField(10);add(lab);add(input);}public boolean action(Event e,Object o){int time=Integer.parseInt(input.getText()); showStatus("");input.setText("");showStatus("模拟次数"+time);t2=t3=t4=t5=t6=t7=t8=t9=t10=t11=t12=0;for(int i=1;i<=time;i++){a=(int)(Math.random()*6+1);b=(int)(Math.random()*6+1);switch(a+b){case 12:t12++;break;case 11:t11++;break;case 10:t10++;break;case 9:t9++;break;case 8:t8++;break;case 7:t7++;break;case 6:t6++;break;case 5:t5++;break;case 4:t4++;break;case 3:t3++;break;case 2:t2++;break;}i12=(double)t12/i;i11=(double)t11/i;i10=(double)t10/i;i9=(double)t9/i;i8=(double)t8/i;i7=(double)t7/i;i6=(double)t6/i;i5=(double)t5/i;i4=(double)t4/i;i3=(double)t3/i;i2=(double)t2/i;repaint();}//repaint();return true;}public void paint(Graphics g){g.drawString("各种和的概率:",25,40);g.drawString("12:"+i12,25,55);g.drawString("11:"+i11,25,70);g.drawString("10:"+i10,25,85);g.drawString("9:"+i9,25,100);g.drawString("8:"+i8,25,115);g.drawString("7:"+i7,25,130);g.drawString("6:"+i6,25,145);g.drawString("5:"+i5,25,160);g.drawString("4:"+i4,25,175);g.drawString("3:"+i3,25,190);g.drawString("2:"+i2,25,205);}}运行结果:三一、实验内容:1.采用循环语句打印如下图形:* *** ***** ******* ****2.编写一个applet,采用公式:e x=1+x1/1!+x2/2!+……..+x n/n!.三、实验步骤:1.程序:package cp3;import java.awt.*;import java.applet.*;public class a1 extends Applet{Label lab;TextField input;int a,b[]=new int[20],i,j;public void init(){lab=new Label("输入数字");input=new TextField(10);add(lab);add(input);}public boolean action(Event e,Object o){a=Integer.parseInt(input.getText());input.setText("");repaint();return true;}public void paint(Graphics g){for(int i=0;a!=0;i++){b[i]=a%10;a/=10;}for(j=0;b[j]!=0;j++);for(int t=--j;t>=0;t--){g.drawString(Integer.toString(b[t]),j*20-t*20,55); }for(i=0;i<b.length;i++){b[i]=0;}}}运行结果:* *** ***** ******* ********* *****2:程序:package cp3;import java.awt.*;import java.applet.*;public class a6 extends Applet{Label lab1,lab2;TextField input1,input2;int a,b,i;double sum=0;public class aa{int mult(int n){int s=1;for(int j=1;j<=n;j++)s*=j;return s;}}public void init(){lab1=new Label("输入x大小");input1=new TextField(10);lab2=new Label("输入n值");input2=new TextField(10);add(lab1);add(input1);add(lab2);add(input2);}public boolean action(Event e,Object o){a=Integer.parseInt(input1.getText()); b=Integer.parseInt(input2.getText()); input1.setText("");input2.setText("");showStatus("");sum=0;aa c=new aa();for(i=0;i<=b;i++){sum+=(double)(Math.pow(a,i))/(double)c.mult(i);}showStatus("结果为"+sum);return true;}}输入x=1,n=30时的运行结果:四二、实验内容:1.定义一个类,它包含了一个int类型的变量x、若干个构造函数(根据你的需要)和一个输出方法show( )。
编程:从键盘输入一个数,将这个数传递给这个类的x,采用方法show( )逆序输出这个数。