QuestionQuestion

Homework #8
Demo: The following code is a procedural way of writing code. It prints the weekly temperature, finds the min and max, and the average as well.

int weeklyTemp [ ] = { 69, 70, 71, 68, 66, 71, 70 };            
int i, max = 0, min = 0;

// print temperatures
for (i = 0; i < weeklyTemp.length; i++) {
       System.out.printf("\nThe temperature on day %d " +
                                        "was %d: ", i + 1,
                         weeklyTemp[i]);
} System.out.printf("\n\n");

// find the max, min temperature
for (i = 0; i < 7; i++) {
       if (i == 0)
             max = min = weeklyTemp[i];
       if (weeklyTemp[i] > max)
             max = weeklyTemp[i];
       if (weeklyTemp[i] < min)
             min = weeklyTemp[i];
}
System.out.printf("The Minimum temperature is: %d\n", min);
System.out.printf("The Maximum temperature is: %d\n", max);

// get average
float total = 0, average;
for (i = 0; i < 7; i++)
       total += weeklyTemp[i];
average = total / weeklyTemp.length;
System.out.println("The average temperage for the week is:
                                  " + average);

8.1 Now, modify the above code, which is all in one place, and break it into multiple methods. Try to convert each piece of important code into static method.

a) Write a method called getTemperatures. Which asks the user to enter 7 temperatures for the week
b) Write a method called printTemperatures. Which prints the 7 temperatures for the week:
c) Write a method called getMax. which returns the maximum temperature of the week.
d) Write a method called getMin. which returns the minimum temperature of the week.
e) Write a method called getAverage, which returns the average temperature of the week.
f) Write a method called printStatistics that prints minimum, maximum and average of the week using above method
g) Write the code in main to call all these functions

Demo: Here is the solution for Homework# 4.6. It is written as a procedural program.
System.out.println("\nUsing for-loop and user values:
                               ");
int x, y;
char hChar1, vChar1; int ht1, wd1;
char answer = 'y';

Scanner input1 = new Scanner(System.in);

while (answer == 'y') {
       System.out.print("\nPlease enter height of a
                                  box: ");
       ht1 = input1.nextInt();
       System.out.print("\nPlease enter width of a box:
                                  ");
       wd1 = input1.nextInt();
       input1.nextLine(); //clean the buffer
       System.out.print("\nPlease enter the horizontal
                                  charcters to draw box: ");
       hChar1 = input1.nextLine().charAt(0);
       System.out.print("\nPlease enter the vertical
                            charcters to draw box: ");

       vChar1 = input1.nextLine().charAt(0);
       for (x=1; x<= wd1;x++)
       {
             System.out.print("" + hChar1);
       }
       System.out.print("\n");
       for(x=1;x<= ht1-2;x++)
       {
             System.out.print(""+ vChar1);
             for (y=1;y <= wd1-2;y++)
                   System.out.print(" ");
             System.out.print("" + vChar1 + "\n");
      }
    for(x=1;x<= wd1;x++)
    {
          System.out.print(hChar1);
      }
      System.out.print("\n\n");
      System.out.print("Continue? Type 'y' for yes:
                            ");
      answer = input1.nextLine().charAt(0);
}
System.out.println("\n\nThank you for using my draw box program");

8.2 Now, modify and break the above code into four methods:
a) A method, drawHorizontalLine that draws horizontal lines
"-----------"
b)    A method, drawVerticalLine that draws vertical lines
          "|       |"
          "|       |"
          "|       |"
c) A method, draw Box, which calls the draw Horizontal Line, and draw Vertical Line to draw the box
d) Call draw Box from main

Homework #9
(Directly helps with your final)
There are three distinct areas you need to research and focus on to get your final done properly:
• Process command line arguments to get the names of input and output files from the user using Elipse
• Read and write information from and into the disk files
• Parse the data read from input file, store in a variable, process it and then print it on the screen and into the output file.

Here are couple of exercises, which will help you in writing code for the above problems.

9.1 Write a class named Exercise5. Your main method’s header looks like this:
               public static void main(String[] args)
      where, args is the String array of command line arguments passed by JVM. Write a
      method processCLArguments() like this:
                public static void processCLArguments(String[] args)
      if the command args contains less than two strings, it displays the message like this:
                Usage: java Exercise5 inputFile outputFile
    If the arguments contains input and output file names it displays the message like this:
                Input will be read from: input_final.txt
               Output will be written into: output_final.txt
9. 2 Write another static method called processInputOutputFiles(), which takes a String array as arguments which has names of input and output files.
public static void processInputOutputFiles(String[ ] args)
It reads the content of the input file whose name is in the first element of args String array with the scores for unknown number of students like the following. The format of the data is, name of a student, followed by comma-separated scores of quiz1, quiz2, quiz3, quiz4, midterm 1, midterm 2 and final for that student:

                   Thui Bhu, 100, 90, 80, 100, 89, 99, 88
                   Ariana B. Smith, 90, 90, 100, 100, 99, 100, 95
                   //more students data

Read each line (scores of a student) at a time, and

a) display the output on the screen like this:
         Student #: 1 Thui Bhu, 100, 90, 80, 100, 89, 99, 88
         Student #: 2 Ariana B. Smith, 90, 90, 100, 100, 99, 100, 95

b) and print the output on the disk file whose name is given in the second element of args String array. The disk output looks like this:
       Student #1 is: "Thui Bhu" whose raw scores are: 100: 90: 80: 100: 89: 99: 88:
       Student #2 is: "Ariana B. Smith" whose raw scores are: 90: 90: 100: 100: 99: 100: 95:

9.3 Research on how to give the command line arguments in your class file using Eclipse.

When starting a Java application, you may want to supply few input parameters to your application even before your program starts. For example, giving database names, supplying username and password etc.
Supplying these arguments before the application starts differs in the way you start your application. You can run your Java application through command window (Windows) or terminal window (MAC). You can even supply these arguments while running from your favorite IDE, e.g.Eclipse.

So, there are two questions:
a) How do you supply these arguments to your program, and
b) How do you process these arguments in your program

Programming Assignment: Final Project
Determine Letter Grades

Summary: Write a program that will determine the letter grade of students of a class (university class, not java class) using your understanding of class (java class), objects, exception handling, and collection in Java.

Description: Your program will need to accept two command line arguments. The first argument will be the name of a disk file that contains the names of students, and their test scores, separated by commas followed by one or more spaces. Each line in the file will contain scores for one student. The second argument will be the name of an output disk file. Your program will create a new output disk file using that name. The output file will have grade information of all students whose information was read from input file, in a sorted order. You will be writing one line in the output file for one student. You will write name of one student and the letter grade he/she got in the class in each line (you should format the texts in the output file). The format of the data in the input file is fixed, however the number of students in the input file is unknown during compile time. The name of input and output files could be anything and only known during run time. Besides writing to the output file, you will also need to display the averages of scores along with minimum and maximum scores for each test in the screen/console.

Calculation: The test scores are weighed. There are four quizzes, 40% total, midterm I is 20%, midterm II is 15% and the final is 25%. All scores in the input file are recorded out of 100. You need to apply the weight for each score in the program to calculate the final score. The final score is tabulated as follows:
Final Score = quiz1 * .10 + quiz2 * .10 + quiz3 * .10 + quiz4 * .10 + midi * .20 + midii * .15 + final * .25 Determination of letter grade is according to the following logic:
Final Score >= 90% then letter grade is A, 80%-89% B, 70%-79% C, 60-69% D, <= 59% F

Sample input data file: input_data.txt (the input data format is: name, quiz1, quiz2, quiz3, quiz4, midi, midii, final,e.g.:

Thui Bhu,               100, 90, 80, 100, 89, 99, 88
Ariana B. Smith,    90, 90, 100, 100, 99, 100, 95
Emily Gonzales,    100, 90, 100, 70, 78, 78, 80
Jennifer L,               80, 90, 90, 100, 89, 99, 85
Maria Jones,          65, 72, 77, 68, 62, 70, 65
Bill Gates,               60, 54, 38, 62, 65, 60, 50
Escobar Morris,      83, 77, 88, 76, 79, 72, 76
Anne Latner,          80, 80, 85, 95, 90, 95, 90

<<more if there are more students>>

Note about input file: You can use the above data as template to create your input file. You can use any text editor of your choice including IDE. You can assume the data will be correctly formatted as described above when I test your program, however, I will have my own input file, with different name and different number of students. You should keep the input file in your project’s default folder when testing using IDE. Refer to the separate document provided which shows you how to set the command line arguments to pass the input and output file names to your program.

Sample output file: output_data.txt (the output format is: Name: letter grade, sorted by name), e.g.

Letter grade for 8 students given in input_data.txt file is:

Anne Latner:                B
Ariana B. Smith:          A

Bill Gates :                   F
Emily Gonzales :          B
Escobar Morris:            C
Jennifer L:                     B
Maria Jones:                D
Thui Bhu:                      A

<<more if there are more students>>

Sample Run of the program (name of the application is TestLetterGrader): Remember that there are two sets of outputs. Letter grade is written in the output disk file (which is not shown in the screen), and score averages are displayed on the console (and are not written in the disk file). Here is an example of run in the command line you could also run this from your IDE (e.g. eclipse). You just need to provide these arguments in the class properties.

Example Run 1:
C:>java TestLetterGrader input_data.txt output_data.txt

Letter grade has been calculated for students listed in input file input_data.txt and written to output   file output_data.txt

Here is the class averages:
                                     Q1          Q2          Q3          Q4          MidI          MidII          Final
Average:                     82.25    80.38      82.25      83.88       81.38       84.13       78. 63      
Minimum                         60          54          38            62          62            60             50
Maximum                      100          90         100         100          99          100             95   

Press ENTER to continue . . .
C:>_

Sample Run 2:
      C:>java TestLetterGrader data1.txt data2.txt

Letter grade has been calculated for students listed in input file data1.txt and written to output file data2.txt
Here is the class averages:
                                     Q1          Q2          Q3          Q4          MidI          MidII          Final
Average:                     82.25    80.38      82.25      83.88       81.38       84.13       78. 63      
Minimum                         60          54          38            62          62            60             50
Maximum                      100          90         100         100          99          100             95   

Press ENTER to continue . . .

C:>_

Design Suggestion: You need to model this problem into a software application – TestLetterGrader (driver class). Your final program should be implemented as Object Oriented and are instantiated using new. The driver class, TestLetterGrader, uses your main class, LetterGrader , which really determines the grade – meaning LetterGrader has all the code to determine the grader, TestLetterGrader simply uses the LetterGrader.

You need to identify classes, their hierarchies (inheritance and/or interface) to be used. The driver class will simply parse the command line arguments and use the main class to read the student’s scores, do the calculation, output the result and close the files. Only TestLetterGrader and LetterGrader class are needed to be public classes. You will need only one main method in the application and that should be in the TestLetterGrader class only. You can have a main in LetterGrader for testing purposes, but, it will not be used when your application, the driver class, TestLettergrader is run.

An simplified pseudo code for the driver class (TestLettergrader.java), your application, may look like this:

public class TestLetterGrader {
       public static void main (String args[]) {
                //test if there are two valid arguments then, create the object
               //if not give right message and exit
               LetterGrader letterGrader = new LetterGrader(args[0], args[1]);
                                                                                        //LetterGrader is your main class,
                                                                                        //args[0] has input file name, and
                                                                                        //args[1] has output file name

               letterGrader.readScore();                //reads score and stores the data in member variables
               letterGrader.calcLetterGrade();      //determines letter grade and stores information
               letterGrader.printGrade();             //writes the grade in output file
               letterGrader.displayAverages();    //displays the averages in console
               letterGrader.doCleanup();            //use it to close files and other resources

                //remember you need to take care of any errors or exceptions
               // in any of these activities must be taken care of
      }
   }

Solution PreviewSolution Preview

These solutions may offer step-by-step problem-solving explanations or good writing examples that include modern styles of formatting and construction of bibliographies out of text citations and references. Students may use these solutions for personal skill-building and practice. Unethical use is strictly forbidden.

package homework9;

import java.io.File;
import java.io.FileWriter;
import java.util.Scanner;

public class Exercise5 {

public static void processCLArguments(String[] args) {
if (args.length < 2) {
System.out.println("Usage: java Exercise5 inputFile outputFile");
} else {
System.out.println("Input will be read from: " + args[0]);
System.out.println("Output will be written into: " + args[1]);
}
}

public static void processInputOutputFiles(String[] args) {
String inputFile = args[0];
String outputFile = args[1];
try {
System.out.println("");
Scanner s = new Scanner(new File(inputFile));
FileWriter fw = new FileWriter(outputFile);
int n = 0;
while (s.hasNextLine()) {
n++;
String line = s.nextLine();
System.out.println("Student #: " + n + " " + line);
String[] params = line.split(",");
fw.write("Student #" + n + " is: \"" + params[0] + "\" whose raw scores are:");
for (int i = 1; i < params.length; i++) {
fw.write(" " + params[i].trim() + ":");
}
fw.write("\r\n");
}
fw.close();
s.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}...

By purchasing this solution you'll be able to access the following files:
Solution.zip.

50% discount

Hours
Minutes
Seconds
$67.50 $33.75
for this solution

PayPal, G Pay, ApplePay, Amazon Pay, and all major credit cards accepted.

Find A Tutor

View available Java Programming Tutors

Get College Homework Help.

Are you sure you don't want to upload any files?

Fast tutor response requires as much info as possible.

Decision:
Upload a file
Continue without uploading

SUBMIT YOUR HOMEWORK
We couldn't find that subject.
Please select the best match from the list below.

We'll send you an email right away. If it's not in your inbox, check your spam folder.

  • 1
  • 2
  • 3
Live Chats