Write a set of static methods

Assignment Help JAVA Programming
Reference no: EM132732891

Computer Programming I

Assignment

• complete the questions below, with marks for each distributed against,
- providing valid solutions, that are well-written and for programs that are efficient and well-structured
- programs with proper & adequate documentation (program header & comments), and well-named identifiers - when required, clear & informative user interaction (clear prompts)
- sufficient output capture showing/proving program solutions solve the given problem

• some questions may have multiple parts, and with marks given across all parts included in the solution
(partial marks given for parts completed...output capture still required to show functionality for your completed work)
• some examples use display() / displayln () in place of .print() / .println(); you are not required to implement these methods, and can continue using .print() / .println() in your code
• SPECIAL to make your code shorter, you can use the utility Exam. Download and compile the source code (Exam.java). Refer to the API document the describes the various methods (Exam.pdf)
• There are three (3) sections: short-programming (4 questions), long-programming (2 questions), and personal programming
So,
In the questions below, do as much as possible given the time, but marks as best given to complete questions. Focus on high-mark questions, but don't neglect low-mark easy questions.
As mentioned above, marks are given to code formatting, commenting, and providing a clean solution-a badly prepared & presented program looks almost like an incorrect program.

Short programming

Implement the following methods. Write a test application to contain ALL the methods, TestMethod.java, with a main() method containing sample calls to verify each method, testing that they execute properly, perform proper operations, and return correct values (where necessary).

Question 1: Write approxPI(), a static method using a simple formula to return an approximate value of π. The method has a single int parameter n, the number of terms used to calculate π, and returns a double value.

The simple formula (see notation), is expressed as:
Step 1: a simple loop (i=0; i<=n) for the summation (∑), stored to the variable pSum, of the terms: (-1)i / (2i + 1)
pSum = 1/1 + -1/3 + 1/5 + -1/7 + 1/9 + -1/11 + 1/13 ... (up to, and include, number of terms: n)
i=0 i=1 i=2 i=3 i=4 i=5 i=6 ... i <= n

Step 2: after the summation, multiple by 4 to obtain the final approximation,
piApprox = (4 * pSum)
Hint: Be cautious of integer-division problems, and use Math.pow(x,y) (xy) to calculate (-1)i

Example calls to the method:
displayln ( "n=1: " + approxPI(1) ); // 2.666666666666667 displayln ( "n=10: " + approxPI(10) ); // 3.232315809405594 displayln ( "n=50: " + approxPI(50) ); // 3.1611986129870506

Question 2: Write a static method asciiGraph(), to display a "graph" of ASCII values of a String. The method has a
single String parameter str, and returns nothing (void).
The method loops through all characters in str, and for each displays a line of *s on a row equal to the ASCII/Unicode integer value of the character being examined (see example).

Hints:
- recall the String methods .charAt() and .length(), and casting a char with (int) directly returns the int ASCII/Unicode value - to produce the line of *s, call the method starLine() from the Exam utility class
- in the output capture document, consider reducing the font size to 7 or 8 point to have each row of *s on a single line

Consider the strings "Ab C" and "TED 99", that are composed of:
A displays 65 stars (*), since Unicode 65 = 'A' b 98 stars (*), since Unicode 98 = 'b'
space 32 * , since Unicode 32 = ' ' (the space) C 67 * , 67 = 'C'

T 84 * , 84 = 'T' E 69 * , 69 = 'E' D 68 * , 68 = ' D' space 32 * , 32 = ' '
9 57 * , 57 = '9'
9 57 * , 57 = '9'

Question 3: Write a set of static methods, to make console input simpler.

Assume the only console input method using the Scanner class is inputString(), shown below; include in your solution. This means you are not permitted to use the Scanner class in any of your methods.

public static String inputString () {
Scanner scan = new Scanner (System.in); // attach to console
return ( scan.next() ); // return next string from input console stream }

Example of calling and testing this method in your main():
String str = inputString(); // get input from console, assign to str displayln ("Input A is: " + str); // display input string
displayln ("Input B is: " + inputString() ); // get input and display

Implement the following static methods, and include statements to test each (such as the example abobe). Input method headers:

- public static int inputInt () - inputs an int from the consle
- public static double inputDouble () - inputs a double from the console
- public static char inputChar () - inputs a single char (character) from the console - public static boolean inputBool () - inputs a boolean values (true, false)
Combo prompt & input method headers:
- public static int inputInt (String prompt) - displays the prompt to the console, and inputs an int
- public static int inputDouble (String prompt) - displays the prompt to the console, and inputs a double

Question 4: Write a method calcMinMaxAvg(), to determine the minimum, maximum, and average value from a list of values in an array. The method has a single String parameter (fileName), returns no value (void), and performs all operations within itself (essentially, this is a mini main() method).

In your application main() method,
- call Exam.fillRandomFile("randomvalsA.txt", 10, -5, 5); filling a file (randomvalsA.txt) with random ##'s in the range -5..5
o this is just an example, for testing purposes; open the file in an editor and manually determine min, max, average o rename the file (in the operating system) to randomvalsB.txt
- when your methods is ready, add a call to it with the desired data filename: calcMinMaxAvg("randomvalsB.txt");
o you can add multiple calls to the method, testing each of the random files you create

Within the method,
- load an array (values) with the values stored in the file, call int[ ] values = Exam.readIntArrayFromFile(fileName);
- use your knowledge of arrays, and determining the min, max, and average calculation, to process the elements in the array
to determine these values
- display the results to the console,
o "For file: ###############, minimum value: ####, maximum value: ####, and average: ####.##"
(showing average to 2 decimal places)

Long programming

Question 1:
Using the methods pickDir() and exractInt() as shown below, to write a simple automated game:
how long does it take a robot to travel from a left line of a field to the right line?

Assume field is 15 units apart (metres, kilometres, it doesn't matter), and the robot starts on the left line.

Write the main() method that keeps looping until the robot's random left and right movements have the robot move past the right line, using the following rules:
• starting travel distance (Trav) is zero (0)-the robot is starting on the left line
• maximum distance, when picking a random direction, is 9 units
• robot moves to the left (L) are negative integer distances (-) to the travel distance, and robot moves to the right (R) are positive integer distances (+) to the travel distance
• robot moves up (U) and down (D) do not affect the left-right travel distance-but they are still displayed
• keep looping while the robot's travel distance <= 15 units (i.e., stop when travel distance > 15 units)
o after the loop, display "robot has crossed the right line!"
• in each loop iteration, the robot picks a new random direction (Rand), by calling pickDir()
o hint: .charAt(), and method extractInt() (see previous question) for direction & distance
• since the robot is travelling randomly, there is a possibility it may never cross the right line (or take a very, very, very long to cross), and it will run out of power,
o add another condition to the loop, stopping if the number of iterations exceeds MAXLOOPS
(set MAXLOOPS to 20, 50, or 100, depending on how much power the robot's battery contains)
o if the exceeding MAXLOOPS, display "battery power depleted, robot has stopped."

Question 2:
Complete one, but not both, of either: Part 1 - Parallel Arrays OR Part 2 - Array of objects.

To help a friend in their astronomy course, you write a program to produce a summary report of the solar system (yes, Pluto is a planet, dammit!). Use anything from the previous questions, any additional methods you find useful, and your knowledge of Java.

Part 1 - Parallel Arrays:
Place the following parallel arrays as globals in your program class (before the main() ).
// name of planet
static String[] planet ={ "Mercury","Venus","Earth","Mars","Jupiter","Saturn","Uranus","Neptune","Pluto" };
// diameter in kilometres
static int[] diamKM ={ 4878, 12104, 12760, 6787, 139822, 120500, 51120, 49530, 2301 };
// orbit time (in Earth years)
static double[] orbitYR ={ 0.241, 0.616, 1.0, 1.88, 11.9, 29.5, 84.0, 165.0, 248.0 };

In the main(),
Sub A: convert from orbit in years to orbit in days,
- declare a new int array orbitDays[ ] using the length of orbitYR[ ] array
- populate the new array with the values of the orbitYR[ ] array converted to days,
- orbit in days = (orbit in years * 365)

Sub B: use the orbitDays[ ] array and planet[ ] (name) array,
- planet with minimum orbit, determine: minOrbit and nameMinOrbit
- planet with maximum orbit, determine: maxOrbit and nameMaxOrbit

Sub C: using the outcomes from the above, generate a summary report (send to a report file)
- display the orbit in days; ex: Earth orbit is 365 days, Mars orbit is 686 days - planet name is shown in UPPERCASE
- diameter is shown in x/1000's of kms in format 7.2f (2 decimal places); ex: Mercury's diam (4878 kms) is 4.88 - the report is displayed on the console, and sent to a file (planetreport.txt)
- use a common output string, which contains the output, to easily send to console and report file - use Exam.writeStringToFile("planets.txt") to send the report to the file

Part 2 - Array of Objects:
Place the following static array of objects as a global in your program class (before the main() ).

// "solar bodies" for the planets, loaded as an initializer list using the SB constructor: // SB (planet name, diameter in kms, orbit in years)
public static SB[] planets =
{ new SB("Mercury",4878,0.241), new SB("Venus",12104,0.616), new SB("Earth",12760,1.0),
new SB("Mars",6787,1.88), new SB("Jupiter",139822,11.9), new SB("Saturn",120500, 29.5),
new SB("Uranus",51120,84.0), new SB("Neptune",49530,165.0), new SB("Pluto",2301,248.0) };

Sub A: write the new proper class SB (solar bodies), used to encapsulate a single "solar body" (i.e., a planet), with the following Attributes (variables):
- name (name of body, String) - default ""
- diamKM (diameter of body in kilometres, int) - default 0
- orbitYr (orbit time around sun in Earth years, double) - default = 0.0

methods:
- default constructor, with no parameters
- constructor, with 3 parameters for name, diamKM, and orbitYr; to set corresponding attributes

- getName( ), getDiamKM( ), and getOrbitYr( ) methods to return each of name, diamKM, and orbitYr - getOrbitDays() method to return the int result of: (orbitYr * 365)

- equals(SB other) method returning a Boolean (true or false), comparing this SB object and another SB object:
equal if the (difference between the diamKM values <= 1000kms). To help in the difference calc. use Math.abs()

- toString() method to return a formatted String with data shown nicely,
o ex: "Pluto has a diameter of 2301 kms and an orbit of 90520 days"

Sub B: to test the ability to compare (.equals() ) two solar body objects,
- declare three (3) fictitious planet SB objects:
o Abydos, at 14142 diameter and 0.870 orbit years o Mongo, at 18112 diameter and 3.540 orbit years o Vulcan, at 13347 diameter and 1.320 orbit years
- check if Abydos and Mongo are equal; if so, display "Planets are similar"; else display "Planets are different" - not equal - check if Abydos and Vulcan are equal; if so, display "Planets are similar"; else display "Planets are different" - equal

Sub C: to be used in a main(), write the program segment that processes the planets[ ] array to display,
- the orbit and planet name with minimum orbit in days
- ex: Planet with min orbit: Mercury at 87 days - the diameter and planet with maximum diameter
- ex: Planet with max diam: Jupiter at 139822 kms - the average orbit in years (to 5 decimal places)
- ex: The average planetary orbit is 21986 days

Sub D: display a simple summary of the solar bodies data in the planets[ ] array, to the console and a report file.
- use a common output string, which contains the output, to easily send to console and report file - use Exam.writeStringToFile("planetsreport.txt") to send the report to the file

Personal programming
Throughout the course, you have been asked to write specific programs that solve specific problems.
This is your opportunity to be creative and discuss something you found interesting in the course, but were not asked to complete in an exercise or assignment.
Write a brief statement (two or three sentences), as to why this topic is interesting for you.
Write a complete well-written, well-documented, and personal program that shows off a topic or concept you found intriguing. This is your program, and not something simply copied from the lecture notes or internet (which is easy to check with a google search, so of course: no cheating).
And, as usual, if you have a working program, gather an output capture to really show off the idea.

Attachment:- Computer Science Assignment.rar

Reference no: EM132732891

Questions Cloud

Compute the Cullumber cash debt coverage : Cullumber Company reports the following information: Net cash provided by operating activities $334800. Compute the Cullumber cash debt coverage
Describe one of the outbreaks over the past 20 years : What measures were used to prevent transmission of the virus?the virus i chose is sin nombre virus
How autonomous vehicles might impact the industry : How autonomous vehicles might impact the industry, Think about a "to-be" new opportunity that AVs enable and briefly explain your idea using Kim
Complete the DBO schedule : New past service cost granted in 20X8, negative because benefits were reduced and the liability has declined (356,000). Complete the DBO schedule
Write a set of static methods : Write a test application to contain ALL the methods, TestMethod.java, with a main() method containing sample calls to verify each method
Create a case study on a person with tetanus : Include how they got it, how you test for it, how you treat it, and what happens if you don't treat it
Discuss weaknesses of each form of communication : Explain why marketers would choose to use each form within a consumer products promotion. Illustrate your ideas with specific examples
Citation of verifiable reference : Please do the Write up on the organism (gram-positive Bacillus subtilis as it relates to humans in healthy and/ or diseased state. The write-up on the organism
How international marketing of product may need to change : Survey emerging trends in international marketing and hypothesize, How the international marketing of your product may need to change over time.

Reviews

Write a Review

JAVA Programming Questions & Answers

  Constructor that initializes the three automatic properties

Create a class called Date that adds three pieces of information as automatic properties-a   month (type int), a day (type int) and a year (type int).

  How are they used in javadoc comments

What is a tag and how are they used in Javadoc comments?

  Create your own unique java application to read all data

Create your own unique Java application to read all data from the file echoing the data to standard output. After all data has been read, display how many data were read

  Where the computer stores the list of exceptions

The call stack is where the computer stores the list of exceptions. Overloaded methods have the same name and parameter lists

  Create class account with id balance person and datecreated

Create class Account with id, balance, Person, and dateCreated. Use a static class variable to store the annualInterestRate for all account holders. Provide constructors, setter and getter for the Account class.

  Compute the maximum of two numbers

Write a program that that computes the maximum of two numbers. Create a class called MaxProgram - Print the returned maximum number

  Create an object-oriented and menu-driven java program

300581: Programming Techniques - be object-oriented utilising the classes described in section B (iv) as a minimum. Other classes may also be needed to solve

  What are the differences between constructors and methods

What are the differences between constructors and methods? What is wrong with each of the following programs? Which of the following statements are valid?

  Create a new project in ide named exceptionhandler

Write code to accept numbers as described above from the user. Your code should ensure that only numbers are accepted.

  Create an if-statement and case statement

Draw a line using 4 points, draw a circle or filled circle using diameter and coordinates.Create an if-statement and Case Statement.

  Print member method and a separate println statement

Use the print member method and a separate println statement to output courseStudentss data -

  Recursive method for performing a range search

Suppose you are implementing a 2d-tree (a kd-tree that stores 2D points) where the nodes of the tree store objects of type Pair280.

Free Assignment Quote

Assured A++ Grade

Get guaranteed satisfaction & time on delivery in every assignment order you paid with us! We ensure premium quality solution document along with free turntin report!

All rights reserved! Copyrights ©2019-2020 ExpertsMind IT Educational Pvt Ltd