View the step-by-step solution to:

This program requires to print the given texts taking care of their text alignment settings. To write this program , I first devised an algorithm...

Project No.2: Growing a Mango

This project consists of two parts. The first part is to write the code for class Mango, which is designed for a Mango tree that grows and whose fruits appreciate overtime. The second part is to write the code for class MangoSim, which conducts a simulation of growing various mango trees for a number of years, and produces information as to which mango tree will be the most profitable.

For the first part, we envision that each Mango tree has information about

what kind it is, as a String, how tall the tree is, as an int (in inches), how much a fruit sells for, as an int (in cents).


Each year the tree receives some updates. First, the price appreciates by 1 percent.

Second, the tree grows. The growth in percentage ranges uniformly between 5 percent and 15 percent. However, if the tree grows too tall, it will go beyond the reach for pickers, and so it is trimmed down. We assume that whenever the tree grows taller than 260 inches it is trimmed down to 150 inches.

After the two updates, mangoes are picked and sold. We assume that two fruits are produced per inch of the height of the tree and each fruit is sold at the current price.

The task of this lab is to write a code for the class Mango with the following functionality:

  1. The class has three instance variables, one for the kind, one for the height, and one for the price.
  2. A constructor that takes values for the kind, the height, and the price as parameters and sets these to instance variables.
  3. Three methods for accessing the kind, the height, and the price individually, named getKind(), getHeight(), and getPrice().
  4. A method named process() for executing the two updates and returns as boolean whether the tree has been trimmed, which should consist of two parts: appreciate() for updating the price and grow() for growing and, if necessary, trimming the tree. The latter method should return whether the tree has been trimmed.
  5. A method named getHarvest() for returning the harvest obtained from the tree, which is the number of fruits times the price.


The above idea has been defined in an interface MangoInterface.java . Your code should implement this interface.

Use the following program MangoTest.java for testing your program.

A sample execution produces the following output:

% java MangoTest
Trimmed. kind=Alfonso, height=150, price=404, harvest=121200
Not trimmed. kind=Alfonso, height=171, price=408, harvest=139536
Not trimmed. kind=Alfonso, height=196, price=412, harvest=161504
Not trimmed. kind=Alfonso, height=217, price=416, harvest=180544
Not trimmed. kind=Alfonso, height=241, price=420, harvest=202440
Trimmed. kind=Alfonso, height=150, price=424, harvest=127200
Not trimmed. kind=Alfonso, height=158, price=428, harvest=135248
Not trimmed. kind=Alfonso, height=180, price=432, harvest=155520
Not trimmed. kind=Alfonso, height=195, price=436, harvest=170040
Not trimmed. kind=Alfonso, height=209, price=440, harvest=183920
Not trimmed. kind=Alfonso, height=235, price=444, harvest=208680
Not trimmed. kind=Alfonso, height=248, price=448, harvest=222208
Trimmed. kind=Alfonso, height=150, price=452, harvest=135600
Not trimmed. kind=Alfonso, height=170, price=456, harvest=155040
Not trimmed. kind=Alfonso, height=178, price=460, harvest=163760
Not trimmed. kind=Alfonso, height=196, price=464, harvest=181888
Not trimmed. kind=Alfonso, height=219, price=468, harvest=204984
Not trimmed. kind=Alfonso, height=232, price=472, harvest=219008
Not trimmed. kind=Alfonso, height=248, price=476, harvest=236096
Trimmed. kind=Alfonso, height=150, price=480, harvest=144000


For the second part, MangoSim.java shall take two parameters at the time of running, args[0] being the name of a file that contains the data of mango trees to be simulated and args[1] being the number of years to be simulated. In the mango data file, the first line is the number of mango trees to be simulated and the ensuing lines are the kind, the height, and the yield of each mango. You can use this file to test the code: mangoData.txt .

To conduct the simulation, first an array of mango trees are defined based on the information presented in the file and then data are read. Next, the simulations are conducted and the cumulative harvests of the individual trees are stored in a two dimensional int array by the name of theTotalHarvests. The first dimension (the rows) of this array represents the mangoes, while the second (the columns) the years. The second dimension has length 1 + the number of years specified by the user, and each column represents the cumulative profits of each tree. Naturally, year 0 (column 0, in other words) has harvest 0 for all trees. In each ensuing year, using the grow() method of the class Mango, each tree is grown and harvested, the harvest from that year is added to the total harvest from the previous year and becomes the value for that year's total harvest.

Then after the simulation, the final year's cumulative harvests are examined to find the highest cumulative harvest and the index to the tree with the highest cumulative harvest.

After the simulation has been completed, the results will be printed on screen. The template MangoSim.java has some variables declared and the part for presenting the results already written. What you have to write is the sections numbered 1, 2, 3 indicated in the template. Since Mango.java uses random number generation the results will be different each time a simulation is run, but here is one example mangoSimResult.txt, which is the result of running java MangoSim mangoData.txt

In addition to developing the code, you must submit a paper describing the idea you used in writing the code. You may use a diagram if necessary. The grading will be 1/3 for the paper, 1/3 for the first part of the coding, and 1/3 for the second part of the coding. The code is due at the conclusion of your lab in the second week.

THE CODE FOR THIS PROJECT HAS ALREADY BEEN WRITTEN!

Attached is the answers to this project. They will need to be changed slightly because this was the coding of my friend(make sure it can compile once changed). After this is done, I will need a summary explaining the algorithms used. An example attached file called "brainstorming algorithm" is located here. Same length as the example.


This program requires to print the given texts taking care of their text alignment se±ngs. To write this program , I Frst devised an algorithm where I used three enums to store the types of text alignment I wish to use i.e. LE²T_JUSTI²IED, RIGHT_JUSTI²IED and JUSTI²IED. The text to be forma³ed is stored in a String array whose each element is a word in the text. I use a procedural approach to implement the logic for text forma±ng. Two func´ons are being used: 1. printMain(): This func´on takes the text, intended width per line and the type of text alignment required by the user. This func´on extracts mul´ple lines from the original text by calcula´ng the start and end posi´ons for each line using the required width for each line. It processes forma±ng of each line by calling another func´on printOneLine() and passing the required informa´on to it along with the line number. 2. printOneLine(): This func´on takes input related to each line from printMain() and applies the text alignment se±ngs to the content of each line and prints it on the screen. ²or applying the text alignment se±ngs, it uses an integer array and stores the number of blank spaces required before each word in the line based on the alignment se±ng. ²ollowing is the algorithm used for this program: 1. Begin 2. Ini´alize text alignment enumerators for LE²T_JUSTI²IED forma±ng LE²T_²LUSHED=0 3. Ini´alize text alignment enumerators for RIGHT_JUSTI²IED forma±ng RIGHT_²LUSHED=1 4. Ini´alize text alignment enumerators for JUSTI²IED forma±ng JUSTI²IED=2 5. Ini´alize testString to text to be forma³ed 6. Set width = 0 7. While width < 20 Or width >=72 8. Prompt user for width per line 9. End While loop 10. Call func´on printMain(testString, width, LE²T_²LUSHED) 11. Call func´on printMain(testString, width, RIGHT_²LUSHED) 12. Call func´on printMain(testString, width, JUSTI²IED) 13. End 14. 15. ²unc´on prinMain(text, width, alignment_se±ng) 16. Set current_length=0 17. Set start=0 18. Set end=0 19. Do while there are words in the text with iterator i 20. Word = Extract each word from the text 21. If current_length+ length of Word < width 22. Add length of word to current_length 23. Move end to i+1 24. If last word is being processed 25. Call printOneLine() for this line 26. End If 27. Else If there is only one word to be processed 28. Adjust curret_length and Call printOneLine() for this line 29. Else 30. Set iterator i to i-1 31. Call printOneLine() for this line 32. End If
Background image of page 1
33. Increment Iterator i 34. End While loop 35. End FuncTon printMain 36. 37. FuncTon printOneLine(text, width, start, end, length, linenumber, alignment_se±ng) 38. IniTalize integer arrays gaps of size = end-start 39. If alignment_se±ng = RIGH²_FLUSHED 40. Set gaps[0] = width-length 41. Else If alignment_se±ng = JUS²IFIED 42. IniTalize gaps according to posiTon of word and line number 43. End funcTon printOneLine While converTng the above algorithm to code, I encountered some problems. Basically, as there were few lines with their last words ge±ng spawned to the next line as the length of the word was jumped over the width speci³ed by the user, the statement current_length+ length of Word < width was yielding to wrong results. For few lines, where the word was supposed to be included in the next line, it was ge±ng wrongly included in the line being processed currently. ²herefore, it was checked if the word was not the ³rst word of the line, an addiTonal 1 was added to current_length. Secondly, calculaTon of gaps was to be done per line per word. ²he text alignment se±ngs governed this calculaTon. While doing it for JUS²IFIED alignment, it was tricky to calculate how many gaps were needed in the beginning and the end of the line text. I added the following to the algorithm to enable this in the program: if ((end != length of text) && (size>1)) if((width-totalLength)%(size-1)==0) for i in range 1 to size gaps[i]=gaps[i] + (width-totalLength)/(size-1) else for i in range 1 to size gaps[i]=gaps[i] + (int)((width-totalLength)/(size-1)); if (lineCount%2 ==0) for i in range 1 to width-totalLength)%(size-1)) gaps[size-i]=gaps[size-i]+1 else for i in range 1 to width-totalLength)%(size-1)) gaps[i]=gaps[i]+1 end if end if end if ²he code for this program has been based only on scalar and global variables along with use of arrays. String arrays make it easier to extract start and end posiTon of each line.
Background image of page 2
package Mango; public class Mango implements MangoInterface{ private String kind; private int height; private int price; public static int TRIM_LIMIT = 260; public static int TRIM_HEIGHT = 150; public static double MIN_GROWTH_RATE = 0.05; public static double GROWTH_RATE = 0.10; public static double APPRECIATION = 1.01; public static double HARVEST_PER_INCH = 2; Mango(String kind, int height, int price){ this.kind = kind; this.height = height; this.price = price; } public String getKind(){ return kind; } public int getHeight(){ return height; } public int getPrice(){ return price; } public boolean process(){ appreciate(); return grow(); } public void appreciate(){ price = (int)(price * APPRECIATION); } public boolean grow(){ double rate; rate = 1.0 + MIN_GROWTH_RATE + Math.random() * GROWTH_RATE; height = (int)(height * rate); if (height > TRIM_LIMIT){ height = TRIM_HEIGHT; return true; } else { return false; } } public int getHarvest(){ return (int)(HARVEST_PER_INCH * height * price); } }
Background image of page 1
package Mango; public interface MangoInterface { //----------------------------------------------- // Accessors //----------------------------------------------- public String getKind(); public int getHeight(); public int getPrice(); //----------------------------------------------- // Grow the tree //----------------------------------------------- public boolean grow(); //----------------------------------------------- // Update the price //----------------------------------------------- public void appreciate(); //----------------------------------------------- // Process appreciation, growth, trim if necessary // and return whether the tree has been trimmed //----------------------------------------------- public boolean process(); //----------------------------------------------- // compute the harvest //----------------------------------------------- public int getHarvest(); }
Background image of page 1
package Mango; import java.io.*; import java.util.*; // mango growing simulation public class MangoSim { // this method prints a given amount in cents // it splits the number in the dollar part and the cent part // connects them with a "." in between with a possible // leading 0 for the cent value // attaches a $ sign // inserts a comma for every three digits in the dollar amount // and fits in a given width public static void printValue(int width, int v) { System.out.printf("%" + width + "s", String.format("$%,d.%02d", (v / 100), (v % 100))); } // main method public static void main(String[] args) throws FileNotFoundException { // the scanner to read from file Scanner fScan; // the number of years int nYears; // the number of trees int nTrees; // the tree array Mango[] theTrees; // the harvest table. rows = mangos, columns = years int[][] theTotalHarvests; // the largest value in the last year int max; // the index to the tree that gives the largest value int maxIndex; // 1. process args and read data fScan = new Scanner(new File(args[0])); nYears = Integer.parseInt(args[1]); nTrees = fScan.nextInt(); theTrees = new Mango[nTrees]; for (int i = 0; i < nTrees; i++) ; { theTrees[1] = new Mango(fScan.next(), fScan.nextInt(), fScan.nextInt()); } // 2. define theTotalHarvests and conduct simulation theTotalHarvests = new int[nTrees][nYears + 1]; for (int k = 0; k < nTrees; k++) { for (int l = 1; k < nYears; l++) { theTrees[k].process(); theTotalHarvests[k][l] = theTotalHarvests[k][l - 1] + theTrees[k].getHarvest(); } } // 3. find the best max = 0; maxIndex = 0; for (int m = 1; m < nTrees; m++) { if (theTotalHarvests[m][nYears - 1] > max) { max = theTotalHarvests[m][nYears - 1]; maxIndex = m; } // 4. print the result
Background image of page 1
System.out.printf("%16s", "kind"); for (int year = 1; year <= nYears; year++) { System.out.printf("%11s", String.format("Yr%2d", year)); } System.out.println(); for (int tree = 0; tree < nTrees; tree++) { System.out.printf("%-16s", theTrees[tree].getKind()); for (int year = 0; year < nYears; year++) { printValue(11, theTotalHarvests[tree][year]); } System.out.println(); } System.out.printf("The most profitable is %s with the total profit " + "of ", theTrees[maxIndex].getKind()); printValue(11, max); System.out.println(); } } }
Background image of page 2
// class for testing class Mango package Mango; public class MangoTest { public static void main(String[] args) { // create one mango Mango myMango = new Mango("Alfonso", 250, 400); // repeat the method process for 20 years and create output for (int year = 0; year < 20; year ++) { // print whether the tree has been trimmed if (myMango.process()) { System.out.print("Trimmed. "); } else { System.out.print("Not trimmed. "); } // print information System.out.print("kind="+myMango.getKind()); System.out.print(", height=" + myMango.getHeight()); System.out.print(", price=" + myMango.getPrice()); System.out.println(", harvest=" + myMango.getHarvest()); } } }
Background image of page 1
Sign up to view the entire interaction

Top Answer

Please find the answer. Kindly accept the... View the full answer

Answer.zip - Preview not available

Sign up to view the full answer

Why Join Course Hero?

Course Hero has all the homework and study help you need to succeed! We’ve got course-specific notes, study guides, and practice tests along with expert tutors.

-

Educational Resources
  • -

    Study Documents

    Find the best study resources around, tagged to your specific courses. Share your own to gain free Course Hero access.

    Browse Documents
  • -

    Question & Answers

    Get one-on-one homework help from our expert tutors—available online 24/7. Ask your own questions or browse existing Q&A threads. Satisfaction guaranteed!

    Ask a Question
Ask a homework question - tutors are online