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.用类创建对象时。
Java2实用教程(第三版)课后习题参考答案第1章 Java入门1. 开发与运行Java程序需要经过哪些主要步骤和过程?答:(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. Java程序是由什么组成的?一个程序中必须要有public类吗?Java源文件的命名规则是怎样的?答:①Java程序由类组成。
②应用程序可以没有public类;小应用程序一定有一个类是public类(主类)。
③应用程序:如果只有一个类,源文件名与该类的类名相同,拓展名为.java;有多个类时,如果有public类(最多一个),源文件名与public类的类名相同,拓展名是.java;没有public类,源文件名与任何一个类的类名相同即可,拓展名为.java。
小应用程序:源文件名与主类的类名相同,拓展名是.java。
4. 在运行小程序的HTML文件中可以使用codebase属性指定小程序的字节码所驻留的目录。
如果不使用codebase属性,小程序的字节码文件必须和运行它的HTML 文件在同一目录中。
编写一个小程序并将小程序的字节码存放在某个目录中,比如C:\5000;把运行该小程序的HTML文件(注意其中的codebase属性):<applet code=你的小程序的字节码 width=200 height=300 codebase=C:\5000> </applet>存放在另一个目录中。
Java2实用教程(第四版)课后习题1-8章答案最终习题一(第1章)一、问答题1.James Gosling2.需3个步骤:1)用文本编辑器编写源文件。
2)使用javac编译源文件,得到字节码文件。
3)使用解释器运行程序。
3.由类所构成,应用程序必须有一个类含有public static void main(String args[])方法,含有该方法的类称为应用程序的主类。
不一定,但最多有一个public类。
4.Path设置为:以安装的版本为例。
)ClassPath设置为:set classpath=D:\jdk\jre\lib\;.;5..java和.class6. java Bird7.独行风格(大括号独占行)和行尾风格(左大扩号在上一行行尾,右大括号独占行)二、选择题1.B。
2.D。
三、阅读程序1.(a)。
(b)两个字节码,分别是和。
(c)得到“NoSuchMethodError”,得到“NoClassDefFo undError: Xiti/class”,得到“您好,很高兴认识您nice to meet you”习题二(第2章)一、问答题1.用来标识类名、变量名、方法名、类型名、数组名、文件名的有效字符序列称为标识符。
标识符由字母、下划线、美元符号和数字组成,第一个字符不能是数字。
false不是标识符。
2.关键字就是Java语言中已经被赋予特定意义的一些单词,不可以把关键字作为名字来用。
不是关键字。
class implements interface enum extends abstract。
3.boolean,char,byte,short,int,long,float,double。
4.float常量必须用F或f为后缀。
double常量用D或d为后缀,但允许省略后缀。
5.一维数组名.length。
二维数组名.length。
二、选择题1.C。
2.ADF。
3.B。
4.BE。
5.【代码2】【代码3】【代码4】【代码5】。
import java.awt.*;import java.awt.event.*;import java.util.*;public class T7_4 {public static void main(String [] args) {FirstWindow win = new FirstWindow("计算的窗口");}}class FirstWindow extends Frame implements TextListener{ TextArea textA1,textA2;FirstWindow(String s) {setTitle(s);setLayout(new FlowLayout());textA1 = new TextArea(6,15);textA2 = new TextArea(6,15);add(textA1);add(textA2);textA1.addTextListener(this);setBounds(0,0,300,300);setVisible(true);validate();}public void textV alueChanged(TextEvent e) {String s = textA1.getText();StringTokenizer fenxi = new StringTokenizer(s," \n\r");int n = fenxi.countTokens();long sum=0;try{for(int i = 0; i<n; i++) {sum += Long.parseLong(fenxi.nextToken());}textA2.setText("总和" + String.valueOf(sum));double avg = (double)sum/n;textA2.append("\n平均数" + String.valueOf(avg));} catch (NumberFormatException e1) {//System.out.println("输入有误!");System.out.println(s);}}}import java.awt.*;import java.awt.event.*;public class T7_5 {public static void main(String [] args) {new MyFrame("挑单词");}}class MyFrame extends Frame implements ActionListener { TextArea ta1,ta2;Button btn;MyFrame (String s) {super(s);setLayout(new BorderLayout());ta1 = new TextArea(5,15);ta2 = new TextArea(5,15);btn = new Button("追加");btn.addActionListener(this);add(ta1,BorderLayout.EAST);add(ta2,BorderLayout.WEST);add(btn,BorderLayout.SOUTH);setBounds(100,100,300,200);setVisible(true);}public void actionPerformed(ActionEvent e) { String s = ta1.getSelectedText();ta2.append(s);}}//带关闭功能的窗口import java.awt.*;import java.awt.event.*;public class T7_6 {public static void main(String [] args) {new MathWindow("计算");}}class MathWindow extends Frame implements ActionListener {//定义一个类继承于Frame 并实现了接口ActionListenerButton btn_Add,btn_Sub,btn_Mul,btn_Mov;//定义四个表示运算的按钮TextField tf1,tf2,tf3;//定义三个文本框Label l1,l2;//定义两个标签MathWindow(String s) {super(s);//设置标题setLayout(new FlowLayout());//设置窗口模式btn_Add = new Button("加");btn_Sub = new Button("减");btn_Mul = new Button("乘");btn_Mov = new Button("除");//实例化四个表示运算的按钮tf1 = new TextField(8);tf2 = new TextField(8);tf3 = new TextField(8);//实例化三个文本框l1 = new Label("",1);l2 = new Label("=",1);//实例化两个标签add(tf1);add(l1);add(tf2);add(l2);add(tf3);add(btn_Add);add(btn_Sub);add(btn_Mul);add(btn_Mov);//将所需的组件加入到窗口中btn_Add.addActionListener(this);btn_Sub.addActionListener(this);btn_Mul.addActionListener(this);btn_Mov.addActionListener(this);//设置四个表示运算按钮的监视器为本窗口this.addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e) {dispose();//撤销当前窗口}});setBounds(100,100,500,80);//设置窗口大小setResizable(false);//设置窗口大小是否可由用户改变setVisible(true);//设置窗口的显示状态validate();//刷新}public void actionPerformed(ActionEvent e) {//实现ActionListener 接口的方法String s1 = tf1.getText();String s2 = tf2.getText();//获取两个文本框的内容try {long m = Long.parseLong(s1);long n = Long.parseLong(s2);//将获取的文本框的内容转换成长整型if(e.getSource() == btn_Add) {//判断事件的发生源并做出相应的处理l1.setText("+");tf3.setText(String.valueOf(m+n));}else if(e.getSource() == btn_Sub) {l1.setText("-");tf3.setText(String.valueOf(m-n));}else if (e.getSource() == btn_Mul) {l1.setText("x");tf3.setText(String.valueOf(m*n));}else if(e.getSource() == btn_Mov) {l1.setText("/");tf3.setText(String.valueOf(1.0*m/n));}else {System.exit(0);}}catch(NumberFormatException e1) {//异常处理System.out.println("输入数字字符串!");}}}import java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.border.*;public class T7_7 {public static void main(String [] args) {WindowBox wb = new WindowBox("确定");}}class WindowBox extends Frame implements ActionListener { Box baseBox,boxV1,boxV2;TextField tf1,tf2,tf3;Button btn_OK;TextArea ta;WindowBox(String s) {super(s);tf1 = new TextField(12);tf2 = new TextField(12);tf3 = new TextField(12);boxV1 = Box.createV erticalBox();boxV1.add(new Label("姓名"));boxV1.add(Box.createV erticalStrut(8)); boxV1.add(new Label("E_mail"));boxV1.add(Box.createV erticalStrut(8)); boxV1.add(new Label("职业"));boxV2 = Box.createV erticalBox();boxV2.add(tf1);boxV2.add(Box.createV erticalStrut(8)); boxV2.add(tf2);boxV2.add(Box.createV erticalStrut(8)); boxV2.add(tf3);baseBox = Box.createHorizontalBox(); baseBox.add(boxV1);baseBox.add(Box.createHorizontalStrut(10)); baseBox.add(boxV2);setLayout(new FlowLayout());btn_OK = new Button("提交");btn_OK.addActionListener(this);ta = new TextArea(5,20);add(baseBox);add(btn_OK);add(ta);setBounds(120,125,200,260);setResizable(false);setVisible(true);}public void actionPerformed(ActionEvent e) {String regex = "\\w{1,}@\\w{1,}\56\\w{1,}";String name = tf1.getText();String email = tf2.getText();String pos = tf3.getText();if(!email.matches(regex)) {tf2.setText("非法E_mail地址");}else {String total = "姓名:" + name + "\nE_mail:" + email + "\n职业:" + pos;ta.append(total);}}}import java.awt.*;import java.awt.event.*;public class T7_8 {public static void main(String [] args) {new MyFrame("Panel");}}class MyPanel extends Panel implements ActionListener { TextField tf;Button btn;MyPanel() {setLayout(new GridLayout(2,1));tf = new TextField(10);btn = new Button("");add(tf);add(btn);btn.addActionListener(this);setVisible(true);}public void actionPerformed(ActionEvent e) { String label = tf.getText();btn.setLabel(label);}}class MyFrame extends Frame {MyPanel mp1,mp2;MyFrame(String s) {setLayout(new BorderLayout());mp1 = new MyPanel();mp2 = new MyPanel();add(mp1,BorderLayout.EAST);add(mp2,BorderLayout.WEST);pack();setVisible(true);}}import java.awt.*;import java.awt.event.*;public class T7_9 {public static void main(String [] args) { new WindowCanvas("矩形--画图");}}class Mycanvas extends Canvas {int x,y,width,height;Mycanvas() {setBackground(Color.cyan);}public void setX(int x) {this.x = x;}public void setY(int y) {this.y = y;}public void setWidth(int width) {this.width = width;}public void setHeight(int height) {this.height = height;}public void paint(Graphics g) {Color old = g.getColor();g.setColor(Color.red);g.fillRect(x,y,width,height);g.setColor(old);}}class WindowCanvas extends Frame implements ActionListener { Mycanvas canvas;TextField inputX,inputY,inputW,inputH;Button btn_ok;WindowCanvas(String s) {super(s);canvas = new Mycanvas();inputX = new TextField(5);inputY = new TextField(5);inputW = new TextField(5);inputH = new TextField(5);Panel pNorth = new Panel();Panel pSouth = new Panel();pNorth.add(new Label("矩形的坐标:(x,y)")); pNorth.add(inputX);pNorth.add(inputY);pSouth.add(new Label("矩形的宽和高:(w,h)")); pSouth.add(inputW);pSouth.add(inputH);btn_ok = new Button("确定");btn_ok.addActionListener(this);pSouth.add(btn_ok);add(pNorth,BorderLayout.NORTH);add(canvas,BorderLayout.CENTER);add(pSouth,BorderLayout.SOUTH); setBounds(50,50,600,700);setVisible(true);}public void actionPerformed(ActionEvent e) { int x = 0,y = 0,w = 0,h = 0;try{x = Integer.parseInt(inputX.getText());y = Integer.parseInt(inputY.getText());w = Integer.parseInt(inputW.getText());h = Integer.parseInt(inputH.getText());}catch(NumberFormatException e1) {x = 100;y = 100;w = 100;h = 100;}finally {canvas.setX(x);canvas.setY(y);canvas.setWidth(w);canvas.setHeight(h);canvas.repaint();}}}import java.awt.*;import java.awt.event.*;public class T7_10 {public static void main(String [] args) {new WindowList("商品信息");}}class WindowList extends Frame implements ItemListener,ActionListener {List list;TextArea ta;WindowList(String s) {super(s);list = new List(3,false);ta = new TextArea(40,10);list.add("lenovo");list.add("ThinkPad");list.add("IdeaPad");list.addItemListener(this);list.addActionListener(this);add(list,BorderLayout.NORTH);add(ta,BorderLayout.CENTER);setBounds(10,10,300,400);setVisible(true);}public void itemStateChanged(ItemEvent e) { String info = list.getSelectedItem();if(info.equals("lenovo")) {String dis = "价格:3000\n产地:中国";ta.setText(dis);}else if(info.equals("ThinkPad")) {String dis = "价格:7000\n产地:中国+美国";ta.setText(dis);}else {String dis = "价格:5000\n产地:中国香港";ta.setText(dis);}}public void actionPerformed(ActionEvent e) {String info = list.getSelectedItem();if(info.equals("lenovo")) {String dis = "家用笔记本电脑的首选,价格低廉,坚固耐用";ta.setText(dis);}else if(info.equals("ThinkPad")) {String dis = "商用笔记本电脑的首选,安全稳定,性能出色";ta.setText(dis);}else {String dis = "游戏用户的笔记本电脑首选,显卡高端,方便便携,经济实用,稳定出色";ta.setText(dis);}}}import java.awt.*;public class T7_11 {public static void main(String [] args) {new MyComponent("组件的前、背景色");}}class MyComponent extends Frame {Button btn;Label label;TextField tf;TextArea ta;MyComponent(String s) {super(s);setLayout(new GridLayout(2,2));btn = new Button("Button");btn.setBackground(Color.red);btn.setForeground(Color.yellow);add(btn);label = new Label("Label",1);label.setBackground(Color.green);label.setForeground(Color.black);add(label);tf = new TextField("TextField",10);tf.setBackground(Color.yellow);tf.setForeground(Color.darkGray);add(tf);ta = new TextArea("TextArea");ta.setBackground(Color.blue);ta.setForeground(Color.white);add(ta);pack();setVisible(true);}}import java.awt.*;import java.awt.event.*;public class T7_12 {public static void main(String [] args) {MyFrame1 mf = new MyFrame1("移动");}}class MyFrame1 extends Frame implements ActionListener { Button btn_L,btn_M;MyFrame1(String s) {super(s);setLayout(null);btn_L = new Button("移动按钮");btn_M = new Button("Moving!");btn_L.setLocation(10,30);btn_L.setSize(100,30);btn_M.setLocation(150,30);btn_M.setSize(50,20);btn_L.addActionListener(this);add(btn_L);add(btn_M);setBounds(0,100,510,400);setVisible(true);}public void actionPerformed (ActionEvent e) { Point p = btn_M.getLocation();p.x += 1;p.y += 1;btn_M.setLocation(p);}}import java.awt.*;import java.awt.event.*;public class T7_13 {public static void main(String [] args) { new MyFrame("改变圆形颜色");}}class MyCanvas extends Canvas {int x,y,r;Color c = Color.yellow;MyCanvas() {x = 200;y = 200;r = 50;setBackground(Color.yellow);}public void setC(Color c) {this.c = c;}public void paint(Graphics g) {Color old = g.getColor();g.setColor(c);g.fillOval(x,y,2*r,2*r);g.setColor(old);}}class MyFrame extends Frame implements ActionListener { Button btn_red,btn_blue,btn_green;MyCanvas can;MyFrame(String s) {super(s);setLayout(null);btn_red = new Button(" 红");btn_red.setBackground(Color.red);btn_red.setForeground(Color.white);btn_green = new Button(" 绿");btn_green.setBackground(Color.green);btn_green.setForeground(Color.white);btn_blue = new Button(" 蓝");btn_blue.setBackground(Color.blue);btn_blue.setForeground(Color.white);btn_red.setSize(50,30);btn_green.setSize(50,30);btn_blue.setSize(50,30);btn_red.setLocation(20+135,40); btn_green.setLocation(90+135,40); btn_blue.setLocation(160+135,40);btn_red.addActionListener(this); btn_green.addActionListener(this); btn_blue.addActionListener(this);add(btn_red);add(btn_green);add(btn_blue);can = new MyCanvas();can.setBounds(0,80,510,510);add(can);Canvas c = new Canvas();c.setBackground(Color.orange);c.setBounds(0,0,510,80);add(c);setVisible(true);setBounds(50,50,500,580);setResizable(false);}public void actionPerformed(ActionEvent e) { Object obj = e.getSource();if(obj == btn_red) {can.setC(Color.red);can.repaint();}else if(obj == btn_green) {can.setC(Color.green);can.repaint();}else {can.setC(Color.blue);can.repaint();}}}。
第 1 章Java 入门一、选择题1 •下列选项中,不属于Java语言特点的一项是 (C)。
内容,这类程序的框架也都是固定的,而绘制图形在窗口中的位置则需要由用户确定。
)安全性 )分布式(B( A5 • Java语言属于(B )种语言?( C)编译执行(D)面向对象(【解析】Java程序采用解释执行的方法。
在系统编译A )面向机器的语言(B )面向对象的语言(C)面向过程的语言 (Java运行Java程序时,编译器将Java程序转化为字节码,D)面向操作系统的语言【解析】Java 语言是一种纯面向对象的语言。
在运行时,解释器将编译得到的字节码进行解释执行。
6 •下列关于Application和Java2•在语言中,(C )是最基本的元素?Applet程序的说法中不正确的一项是( B (B)包)。
A ()方法(A) Application 使用解释器(C)对象(D)接口java.exe(B) Application。
不使用独立的解释器构成【解析】Java程序的基本元素类(抽象的对象) (3个类和10个方法的Java源文件后,C) Applet在浏览器中运行编译一个定义了3. ( D) Applet 会产生( D )个字节码文件?扩展名是( D )?必须继承Java 的Applet 类【解析】Application程序包含个字节码文件,扩展名为( A) 13.class main()方法,它是一种独立执行的程序,因此必须使用独立的解释器解释执行。
B() 1 个字节码文件,扩展名为.class7•下列选项中,不属于3 (C)个字节码文件,扩展名为.java Java核心包的一项是( A )。
(A 个字节码文件,扩展名为.class ) javax.swing (B) java.io 3 (D) (源文件中的每一个类编译后都会生成一个字【解析】C) java.utile (D) ng【解析】凡是以节码文件,字节码文件的扩展名是.class o java开头的包都是Java核心包,以javax开头的包则属于Java应用程序时,需要用户考虑问题是(.在创建4Applet扩展包。
第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.角谷猜想:任何一个正整数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( )逆序输出这个数。