Java Programming Exercises Part 2 : 12 Questions

Compiled By Unknown - No Comments
  1. Hello World Experimentation *:
  2. Experiment with the Hello.java program to learn the meanings of typical compile­time and runtime error messages.
  3. Research **:
  4. Study Sun’s Java Coding Conventions. You can download this document from http://www.java.sun.com/docs/codeconv/.
  5. Research **:
  6. Study Appendix 5 “Java Coding-Style Conventions.”
  7. Truss Analysis ***:
  8. A good way to support weight on a bridge is to use a truss structure, shown below. For simplicity, we discuss the situation as though there were just one truss. Actually, of course, there are two – one on either side of the road. The loadings we use apply to the whole bridge, so when we conclude that a particular member has a certain load, that load is actually carried by two identical members – one on either side of the road. The solid lines are steel members, and the white arrows are forces. The large up arrow (labeled P) below each end is the pier force, pierForce, that supports one end of the bridge. The large down arrow in the center (labeled L) is the weight of a load halfway across the bridge, centerLoad. Each medium-sized down arrow across the bottom represents the weight of the road and bottom structural members in one of the four sections of the bridge, roadWeight. Each small arrow represents the weight of an above-road structural member, structuralWeight. Each junction is identified by a bold capital letter (A, B, C, D, E, F, G, H, I), and each structural member is identified by a unique pair of these letters. The small lower-case letters in the figure indicate whether a particular steel member is in tension (t) or compression (c). All the bottom (road-level) members are in tension, all the top members are in compression (negative tension), and the diagonal members alternate between tension (insides) and compression (outsides). Since the bridge is stationary, there is no acceleration, and we can analyze it by noting that at each junction, the total force upward must equal zero, and the total force to the right must equal zero. The problem is symmetrical, so it’s sufficient to analyze half of the bridge. Let’s start with vertical forces and go from junction E back to junction A. The vertical force exerted by diagonal DE on junction E is upForceOnEbyED ← centerLoad/2 + roadWeight/2. The centerLoad is divided by 2 because this load is shared by DE and EF. The roadWeight is divided by 2 because half the weight of CE is carried by BC. DE is in tension, so its vertical force on junction E is upward and the sign of this force is positive. The vertical force exerted by diagonal DE on junction D is upForceOnDbyDE ← -upForceOnEbyDE – structuralWeight. The negative signs indicate a reversed and downward force direction, respectively. The structuralWeight term accounts for DE’s own weight. The vertical force exerted by the diagonal CD on junction D is upForceOnDbyCD ← -upForceOnDbyDE + structuralWeight. CD is in compression, so its vertical force on junction D is upward. The structuralWeight is half the weight of DF plus half the weight of BD. Continuing in this fashion, we also have: upForceOnCbyCD ← -upForceOnDbyCD – structuralWeight; upForceOnCbyBC ← -upForceOnCbyCD + roadWeight; upForceOnBbyBC ← -upForceOnCbyBC – structuralWeight; upForceOnBbyAB ← -upForceOnBbyBC + structuralWeight/2; upForceOnAbyAB ← -upForceOnBbyAB - structuralWeight; pierForce ← -upForceOnAbyAB + roadWeight/2. Because AB is sloping, its compressive force pushes down not only on junction A. It also pushes to the left, and this leftward horizontal force is exactly balanced by a rightward horizontal force exerted by AC. This particular truss employs equilateral triangles, so each of its internal angles is 60o. Either trigonometry or the Pythagorean theorem says that the tensile force along the axis of any across-the-road diagonal pair is equal to 1/Sin(60) = 2/sqrt(3) = 1.1547 times the vertical force exerted on the upper end of that member. Thus, tensionAtAinAB ← 1.1547 * upForceOnAbyAB; tensionAtBinBC ← -1.1547 * upForceOnBbyBC; tensionAtCinCD ← 1.1547 * upForceOnCbyCD; tensionAtDinDE ← -1.1547 * upForceOnDbyDE. Also, the horizontal force exerted by any diagonal member is equal to half the axial force or 1/Tan(60) = 1/sqrt(3) = 0.57735 times the vertical force exerted by that member. This gives us equations for the forces in the horizontal members: rightForceOnAbyAC ← -0.57735 * upForceOnAbyAB; rightForceOnCbyAC ← - rightForceOnAbyAC; rightForceOnCbyCE ← - rightForceOnCbyAC + 0.57735 * (upForceOnCbyBC - upForceOnCbyCD); rightForceOnBbyBD ← -0.57735 * (upForceOnBbyAB – upForceOnBbyBC); rightForceOnDbyBD ← -rightForceOnBbyBD; rightForceOnDbyDF ← -rightForceOnDbyBD -0.57735 * (upForceOnDbyCD – upForceOnDbyDE). Since the horizontal forces are along the axes of the horizontal members, we have: tensionAtAinAC ← rightForceOnAbyAC; tensionAtCinCE ← rightForceOnCbyCE; tensionAtBinBD ← rightForceOnBbyBD; tensionAtDinDF ← rightForceOnDbyDF. a) [after §3.16] Using initialized values: Write a Java program that uses named constants for centerLoad, roadWeight, and structuralWeight. Your program should calculate the value of pierForce, plus the tension in all members of the truss. This does not involve fancy mathematics. Just evaluate the expressions and make the assignments in the order in which they have been presented above, using results of previous calculations for the next one. Make your program so that what appears on your computer screen matches the following sample session. The first three lines show the named constant values, and the subsequent lines show values that your program calculates. Sample session: Assumed center load in lbs: 20000 Assumed weight of one section of road in lbs: 2000 Assumed weight of structural pair in lbs: 500 Support for half of bridge = 16750 lbs. Total tension in BD = -17464 lbs. Total tension in DF = -31032 lbs. Total tension in AB = -18186 lbs. Total tension in BC = 17320 lbs. Total tension in CD = -14433 lbs. Total tension in DE = 13279 lbs. Total tension in AC = 9093 lbs. Total tension in CE = 24681 lbs. b) [after §3.23] Using inputs: Modify the program of part A to make it accept inputs that override the initialized values. Make your program so that what appears on your computer screen matches the following sample session. As always, if a sample session contains italicized values, those values indicate user input. Sample session: Enter center load in lbs: 20000 Enter weight of one section of road in lbs: 2000 Enter weight of structural member in lbs: 500 Support for half of bridge = 16750 lbs. Total tension in BD = -17464 lbs. Total tension in DF = -31032 lbs. Total tension in AB = -18186 lbs. Total tension in BC = 17320 lbs. Total tension in CD = -14433 lbs. Total tension in DE = 13279 lbs. Total tension in AC = 9093 lbs. Total tension in CE = 24681 lbs.
  9. Sequence of Commands *:
  10. Consider the following sequence of commands: 1 int a = 5, b = 2; 2 double c = 3.0; 3 4 a += b; 5 b++; 6 c--; 7 c *= a; 8 System.out.println("a + b + c = " + (a + b + c)); a) Trace this sequence, using this header: Use a separate row for each statement. b) Write a Java program that executes these commands on the computer and compare the result with the trace output.
  11. Computer Speed **:
  12. Suppose a program has a certain number of statements, which on average execute many times in repetitions, that is, statementExecutions = (number of statements) x (average repetition count). A compiler translates this into object-code instructions. Since source-code statements often include more than one explicit primitive operation, and there are often many invisible primitive operations in the background, the number of object-code instructions is typically much greater than the number of source code statements. We can represent these effects with the multiplier, instructionsPerStatement. A processor has a particular speed, clockRate. Although some instructions may require several clock cycles to complete, a modern computer often executes more than one instruction in parallel, so a given program on a given computer has an average instructionsPerCycle that may be either less than or greater than unity. The ideal total execution time is: statementExecutions x instructionsPerStatement / (instructionsPerCycle x clockRate ). To this ideal time, we must add whatever time it takes to fetch information not immediately available. For each successful instruction execution, we must add time to account for the chance of not finding something that’s needed. Not finding something in the first-level cache adds: (1 - firstCacheHitFraction) x firstCacheSwapTime. Not finding something in the second-level cache adds: (1 - firstCacheHitFraction) x (1 - secondCacheHitFraction) x secondCacheSwapTime. Not finding something in the main memory adds: (1 - firstCacheHitFraction) x (1 - secondCacheHitFraction) x (1 - mainMemoryHitFraction) x [0.5 / diskSpeed + pageSize/(diskTrackLength x diskSpeed)]. Total incremental time is average incremental time multiplied by: statementExecutions x instructionsPerStatement. a) [after §3.17] Using initialized values: Write a Java program that estimates the total time to run a typical computer program. Note the 12 “assumed” numeric values in the sample session below. Use 12 initialization statements to store those values into 12 variables. No user input is necessary. The bottom two lines are calculated results. Sample session: Assumed executions of source-code statements: 10000 Assumed average instructions/statement: 20.0 Assumed clock rate in megahertz: 2000.0 Assumed average instructions/cycle: 1.0 Assumed first-level cache hit fraction: 0.99 Assumed first-level cache swap time in microsec: 0.0010 Assumed second-level cache hit fraction: 0.999 Assumed second-level cache swap time in microsec: 0.0050 Assumed main memory hit fraction: 0.9999 Assumed main memory page size in bytes/page: 4096 Assumed disk speed in revolutions/sec: 500.0 Assumed disk track length in bytes/revolution: 400000 Ideal execution time = 1.0E-4 seconds. Expected execution time = 1.0221409599999999E-4 seconds. b) [after §3.23] Using inputs: Modify the program of part A to make it accept inputs that override the initialized values. Make your program so that what appears on your computer screen matches the following sample session. As always, if a sample session contains italicized values, those values indicate user input. Sample session: Enter executions of source-code statements: 10000 Enter average instructions/statement: 20 Enter clock rate in megahertz: 2000 Enter average instructions/cycle: 1 Enter first-level cache hit fraction: .99 Enter first-level cache swap time in microsec: .001 Enter second-level cache hit fraction: .999 Enter second-level cache swap time in microsec: .005 Enter main memory hit fraction: .9999 Enter main memory page size in bytes/page: 4096 Enter disk speed in revolutions/sec: 500 Enter disk track length in bytes/revolution: 400000 Ideal execution time = 1.0E-4 seconds. Expected execution time = 1.0221409599999999E-4 seconds.
  13. HVAC Load **:
  14. In this project you will calculate the heating and cooling loads for a typical residence. The wintertime heating load is all of the heat that flows out of the building when the outside temperature is nearly its coldest and when there is no free heat provided by sunshine or internal lights or appliances. The coldest time is typically in the middle of January. The summertime cooling load is all of the heat that flows into the building when the outside temperature is nearly its hottest, the outside humidity is high, there are no clouds to block the sun, and the building is occupied with normal lighting and appliance usage. The hottest time is usually about 3:00 PM in the middle of July. Assume that four design parameters are constant: The winter indoor design temperature is 72oF, the summer indoor design temperature is 76oF, the summer indoor design humidity ratio is 0.01 lbs of water vapor per pound of dry air, and the sunshine coming in through west windows at the design time is 193 BTU/hr / ft2. (This is the value for 40 deg North Latitude at 3:00 PM on July 21.) The remaining design parameters are user inputs: total roof area, building perimeter, building height, total area of windows and doors, total area of west-facing windows, roof U-value, wall U-value, window and door U-value, winter outdoor design temperature, summer outdoor design temperature, summer outdoor humidity ratio, infiltration rate in cubic feet per minute (CFM), number of people present, and electricity in use. Consider doors to be additional windows. The outputs of the program are total heating BTU/hr, total cooling BTU/hr, and the cooling load expressed in the nearest whole number of tons, where one ton = 12,000 BTU/hr. The heating-load components are as follows: roof load ← area * roof U-value * winter temperature difference window load ← area * window U-value * winter temperature difference wall load ← net area * wall U-value * winter temperature difference infiltration load ← CFM * 1.08 * winter temperature difference where: winter temperature difference ← winter indoor design temperature – winter outdoor design temperature net wall area ← building perimeter * building height – window area To provide a factor of safety and to accelerate morning warm up, multiply the total of all of the above heating-load components by a factor of 1.3. The cooling-load components are as follows: roof load ← area * roof U-value * summer temperature difference window load ← area * window U-value * summer temperature difference wall load ← net area * wall U-value * summer temperature difference infiltration temperature load ← CFM * 1.08 * summer temperature difference solar load ← west solar heat gain * west window area electrical load ← 3.416 * Watts people temperature load ← 250 * number of people infiltration humidity load ← CFM * 4675 * summer humidity difference people humidity load ← 200 * number of people where: summer temperature difference ← summer outdoor design temperature – summer indoor design temperature summer humidity difference ← summer outdoor humidity ratio – summer indoor humidity ratio To provide a factor of safety, multiply the total of all of the above cooling-load components by a factor of 1.1. a) [after §3.17] Using initialized values: Write a Java program that calculates summer and winter design loads. Use named constants for the 14 items shown in the first 14 lines below. The bottom three lines are calculated results. Sample session: HVAC Load Calculation: Assumed total roof area in square ft: 1500 Assumed building perimeter in ft: 140 Assumed building height in ft: 18 Assumed total window area in square ft: 400 Assumed west window area in square ft: 80 Assumed roof U-value: 0.04 Assumed wall U-value: 0.10 Assumed window U-value: 0.5 Assumed summer outdoor temperature in deg F: 100 Assumed summer outdoor humidity ratio: 0.013 Assumed winter outdoor temperature in deg F: 2 Assumed infiltration in CFM: 200 Assumed number of people present: 3 Assumed electrical use in Watts: 1500 Heating Load = 62608.0 BTU per hour Cooling Load = 45354.1 BTU per hour or approximately 4 tons b) [after §3.23] Using inputs: Modify the program of part A to make it accept inputs that override the initialized values. Make your program so that what appears on your computer screen matches the following sample session. As always, if a sample session contains italicized values, those values indicate user input. Sample session: HVAC Load Calculation: Enter total roof area in square ft: 1500 Enter building perimeter in ft: 140 Enter building height in ft: 18 Enter total window area in square ft: 400 Enter west window area in square ft: 80 Enter roof U-value: 0.04 Enter wall U-value: 0.10 Enter window U-value: 0.5 Enter summer outdoor temperature in deg F: 100 Enter summer outdoor humidity ratio: 0.013 Enter winter outdoor temperature in deg F: 2 Enter infiltration in CFM: 200 Enter number of people present: 3 Enter electrical use in Watts: 1500 Heating Load = 62608.0 BTU per hour Cooling Load = 45354.1 BTU per hour or approximately 4 tons
  15. Campaign Planning ***:
  16. To run an effective political campaign, it’s important to plan well and use resources efficiently. Don’t waste time and money on those who probably won’t vote, will probably vote for you, or will probably vote against you. Focus on those who are likely to vote and who are currently undecided. Start by using electronically available historical voting information to assign each potential voter to one of four “pools”: 1. members of your party who vote regularly; 2. independents who vote regularly; 3. members of your party who vote occasionally; 4. everybody else. Gather money and support from pool 1. Then, use telephone polling to qualify individual voters as “yes,” “no,” or “maybe,” and focus money and labor on “maybe” voters in pool 2. Use the following named constants (named constants are described in §3.14): REGULAR_TURNOUT_FRACTION = 0.833 DOLLARS_PER_SOLICITATION = 5.00 CLERICAL_HOURS_PER_CALL = 0.05 TELEPHONE_HOURS_PER_CALL = 0.1 TRANSPORT_HOURS_PER_CALL = 0.05 OVERHEAD_FRACTION = 0.25 After gathering historical data and estimating the fraction of votes in different pools, compute otherTurnoutFraction ← (probableVoters – REGULAR_TURNOUT_FRACTION * (ourPartyRegulars + independentRegulars)) / (totalRegistered – (ourPartyRegulars + independentRegulars)) Then, output expected numbers of votes from each pool to clarify the situation. After documenting expected funding, decide on allocation of worker labor among the four pools. Input integers zero or one only, multiply these inputs by respective pool size, and accumulate to generate a total number of “calls”. Then, use the predefined constants to determine the total number of labor hours required in each type of work. Assume the time for each solicitation call is twice that for other calls, each poll watcher spends 10 hours, and the overhead time is the multiplier times the sum of all other times. (Decisions about how to use the money raised are not included. The poll watcher and substantial clerical times are devoted to progressively shortening voter lists as polling identifies individuals who want to vote but haven’t decided which way or need transportation to the voting place.) a) [after §3.17] Using initialized values: Write a Java program to help organize estimates of votes, money, and labor. Use named constants for historical data and estimated fraction of votes in different voting pools. More specifically, use named constants for the first 10 numeric values shown below. The six lines under Expected Votes are calculated values. Use two more named constants for the first two numeric values under Expected Funding. The third value under Expected Funding is calculated. Use four more named constants for the four numeric values under Work Plan. The first six of the last eight lines are calculated results. The next to last line displays a final named constant, and the last line is a result calculated from it. Sample session: POLITICAL CAMPAIGN PLANNER Assumed total number of registered voters: 5000 Assumed registered voters in our party: 1500 Assumed registered independent voters: 2000 Assumed number of regular voters in our party (voting probability = 0.833): 900 Assumed number of regular independent voters (voting probability = 0.833): 1000 Assumed average number of actual voters: 2000 Assumed expected fraction of our party regular votes: 1.0 Assumed expected fraction of independent regular votes: 0.5 Assumed expected fraction of our party occasional votes: 0.6 Assumed expected fraction of other votes: 0.1 Expected votes: First pool: regular party votes = 749 Second pool: regular independent votes = 416 Third pool: occasional party votes = 48 Last pool: other votes = 33 total expected votes = 1246 votes needed = 1001 Expected Funding: Assumed number of early $500 donors: 4 Assumed number of solicitation calls: 50 Amount available for campaign = 2250.0 Work Plan: Call first pool assumption [yes:1, no:0]: 1 Call second pool assumption [yes:1, no:0]: 1 Call third pool assumption [yes:1, no:0]: 0 Assumed number of polling places: 2 Clerical hours = 95.0 Telephone hours = 200.0 Poll watcher hours = 20.0 Transport hours = 95.0 Overhead hours = 102.5 Total worker hours = 512.5 Enter number of workers available: 25 Hours per worker = 20 b) [after §3.23] Using inputs: Modify the program of part A to make it accept inputs that override the initialized values. Make your program so that what appears on your computer screen matches the following sample session. As always, if a sample session contains italicized values, those values indicate user input. Sample session: POLITICAL CAMPAIGN PLANNER Enter number of registered voters: 5000 Enter registered voters in our party: 1500 Enter registered independent voters: 2000 Enter number of regular voters in our party (voting probability = 0.833): 900 Enter number of regular independent voters (voting probability = 0.833): 1000 Enter average number of actual voters: 2000 Enter expected fraction of our party regular votes: 1.0 Enter expected fraction of independent regular votes: 0.5 Enter expected fraction of our party occational votes: 0.6 Enter expected fraction of other votes: 0.1 Expected votes: First pool: regular party votes = 749 Second pool: regular independent votes = 416 Third pool: occasional party votes = 48 Last pool: other votes = 33 total expected votes = 1246 votes needed = 1001 Expected Funding: Enter number of early $500 donors: 4 Enter number of solicitation calls: 50 Amount available for campaign = 2250.0 Work Plan: Call first pool? [yes:1, no:0]: 1 Call second pool? [yes:1, no:0]: 1 Call third pool? [yes:1, no:0]: 0 Enter number of polling places: 2 Clerical hours = 95.0 Telephone hours = 200.0 Poll watcher hours = 20.0 Transport hours = 95.0 Overhead hours = 102.5 Total worker hours = 512.5 Enter number of workers available: 25 Hours per worker = 20
  17. String Processing *:
  18. Consider the following code fragment: 1 int a = 20; 2 int b; 3 double x = 3.5; 4 String s = "All"; 5 char ch; 6 7 x += a; 8 x--; 9 a /= 4 - 1; 10 b = s.length(); 11 b += 4; 12 s += "is well"; 13 ch = s.charAt(b); 14 System.out.println("a = " + a + ", b = " + b); 15 System.out.println("x = " + x + "\ns = " + s); 16 System.out.println("ch = " + ch); Trace the above code, using the following format: Use a separate row for each statement. Write a Java program that executes the commands in the code fragment.
  19. Swapping *:
  20. The following pseudocode describes a simple algorithm which swaps the values in two variables, x and y: 1 print “Enter initial value of x: ” 2 input x 3 print “Enter initial value of y: ” 4 input y 5 set temp to x 6 set x to y 7 set y to temp 8 print “x = ” x“, y = ” y a) Trace the above pseudocode for x input of 8 and y input of 3, using the following header: Use a separate row for each line of pseudocode. b) Write a Java Program that implements this algorithm.
  21. Circle Parameters *:
  22. Write a Java program that generates and prints circle-related values. Read in a value for radius. Calculate and print the corresponding values for diameter, circumference, and area. Use the built-in Java constant Math.PI for the value of π. Use Math.PI the same way that you would use 3.1452 in your program – there’s no need to declare Math.PI with a declaration statement, just use it. Sample session: Enter a radius value: 2.5 Diameter = 5.0 Circumference = 15.707963267948966 Area = 19.634954084936208
  23. One-Hundredth Birthday *:
  24. Write a Java program that prompts the user for his/her birthday month, day, and year and prints the date of the user’s one-hundredth birthday. Sample session: Enter the month you were born: March Enter the day you were born: 18 Enter the year you were born: 1986 You will be 100 on March 18, 2086.

Tags:

No Comment to " Java Programming Exercises Part 2 : 12 Questions "