Showing posts with label Methods. Show all posts
Showing posts with label Methods. Show all posts

Monday, June 17, 2013

Java Arrays / FIle input / File output


-->

Java Programming Assignment For Arrays, File Input, And File Output


For use in Eclipse.

A teacher has 10 students who have taken the course.  The teacher uses the following grading scale to assign a letter grade to a students, based on the average of his or her four test scores:
Avg Test score  Letter grade
90-100 A
  1. B
  1. C
  1. D
  1. E

Assume that teacher has stored the following information in different files:
Lname.txt stores last names of students (string)
Fname.txt stores first names of students (string)
Exam1.txt stores exam 1 score (double)
Exam 2.txt stores exam 2 score (double)
Exam 3.txt stores exam 3 score (double)
Exam 4.txt stores exam 4 score (double)

In each case, the corresponding entries match in each file, that means, first element of each file corresponds to the first student, second for second student and so on.
Write a program that reads data from each file and stores in a separate array, except that String array named fullName contains the string representing full name of the student as follows:  "John Kennedy"  where "Kennedy" is picked up from Lname.txt, and "John" is selected from corresponding position in Fname.txt file. Create double arrays named Ex1, Ex2, Ex3, and Ex4 to score corresponding scores read from the files. 

Write the following methods:getAvg (to return average of all elements of an array passed as a parameter), 
getMax  (to find the largest element of an array passed as a parameter),
getMin (to find the smallest element of an array passed as a parameter).
computeAverage method which accepts 4 double parameters (for each exam score) and returns a double value representing the average. computeGrade method which accepts a double value (average) and returns a letter grade (char type). 

Using computeAverage method, compute and store the average for each student in a double array titled exAvg.

Using computeGrade method, compute and store the letter grade for each student in a char array titled grade


Output
After calculating the average test score, and the grade for each student, obtain the following output (on console using printf statement): Tabulated output for students with proper heading (sample output) – first line is the header --

Full Name of Student  Ex1 Ex2 Ex3 Ex4 Avg Grade
John Kennedy 78.0 73.0 83.0 78.0  78.0
(for all students) etc.

Print the statistics for each exam (by using appropriate method calls)

Exam Number  Max. Score  Min Score  Average Score
Exam 1 99.2 43.9 72.9 
Similarly, print these values for Exam 2, Exam 3, Exam 4, and AvgTestScore. 


Creation of Data sets

For each of the data sets, first 5 entries are to be entered as shown—Add another 5 entries of your choice data

Lname.txt Fname.txt Exam1.txt Exam2.txt Exam3.txt Exam4.txt

Gates  Lisa 87 76 92 88

Kramer Bill 65 72 83 64

Winfry Susan 91 90 87 99

Einstein Matt 57 75 79 56

Jobs Cindy 74 84 94 97

(add 5 more entries in each file of your choice)


Make the files yourself using a text edit program on your computer and put them into your project computer in eclipse

Here is the code for the assignment. You'll have to indent it yourself


import java.io.File;

import java.io.IOException;

import java.io.PrintStream;

import java.util.ArrayList;

import java.util.Scanner;



/**

 * 

 * @param args

 */

public class EnterYourClassNameHere{


public static double[] readScoreFile(String fileName) throws IOException {

// Read the file name and store it

double value;
ArrayList<Double> result = new ArrayList<Double>();
Scanner sc = new Scanner(new File(fileName));
while (sc.hasNextDouble()) {
value = sc.nextDouble();
result.add(value);
}
sc.close();
double[] arr = new double[result.size()];
for (int i = 0; i < arr.length; i++) {
arr[i] = result.get(i);
}
return arr;
}
public static ArrayList<String> readFile(String fileName)
throws IOException {
// Read Name and Store names
ArrayList<String> result = new ArrayList<String>();
Scanner sc = new Scanner(new File(fileName));
while (sc.hasNextLine()) {
String line = sc.nextLine().trim();
if (!line.equals("")) {
result.add(line);
}
}
sc.close();
return result;
}
// Read Array full name
public static String[] readFullName(String fnameFile, String lnameFile)
throws Exception {
ArrayList<String> fname = readFile(fnameFile);
ArrayList<String> lname = readFile(lnameFile);
int size = fname.size();
if (size > lname.size()) {
size = lname.size();
}
String[] fullName = new String[size];
for (int i = 0; i < size; i++) {
fullName[i] = fname.get(i) + " " + lname.get(i);
}
return fullName;
}
// return Average
public static double getAvg(double[] arr) {
double sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum / arr.length;
}
// Return max
public static double getMax(double[] arr) {
double max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (max < arr[i]) {
max = arr[i];
}
}
return max;
}
// return Min
public static double getMin(double[] arr) {
double min = arr[0];
for (int i = 1; i < arr.length; i++) {
if (min > arr[i]) {
min = arr[i];
}
}
return min;
}
// Compute Average
public static double computeAverage(double score1, double score2,
double score3, double score4) {
return (score1 + score2 + score3 + score4) / 4;
}
// Score
public static char computeGrade(double score) {
if (score >= 90) {
return 'A';
else if (score > 80) {
return 'B';
else if (score > 70) {
return 'C';
else if (score > 60) {
return 'D';
else {
return 'E';
}
}
// For output
public static void main(String[] args) throws Exception {
String[] fullName = readFullName("Fname.txt""Lname.txt");
double[] Ex1 = readScoreFile("Exam1.txt");
double[] Ex2 = readScoreFile("Exam2.txt");
double[] Ex3 = readScoreFile("Exam3.txt");
double[] Ex4 = readScoreFile("Exam4.txt");
char[] grade = new char[fullName.length];
double[] exAvg = new double[fullName.length];
for (int i = 0; i < grade.length; i++) {
exAvg[i] = computeAverage(Ex1[i], Ex2[i], Ex3[i], Ex4[i]);
grade[i] = computeGrade(exAvg[i]);
}
PrintStream ps = new PrintStream(new File("PA9OutFile.txt"));
System.out
.println("Full Name of Student    Ex1 Ex2 Ex3 Ex4 Avg Grade");
ps.println("Full Name of Student Ex1 Ex2 Ex3 Ex4 Avg Grade");
System.out.println("-----------------------------------------------------------");
ps.println("-----------------------------------------------------------");
for (int i = 0; i < grade.length; i++) {
System.out.println(String.format("%-23s %5.1f %5.1f %5.1f %5.1f %5.1f %c", fullName[i],
Ex1[i], Ex2[i], Ex3[i], Ex4[i], exAvg[i], grade[i]));
ps.println(String.format("%-23s %5.1f %5.1f %5.1f %5.1f %5.1f %c",
fullName[i], Ex1[i], Ex2[i], Ex3[i], Ex4[i], exAvg[i],grade[i]));
}
System.out.println();
ps.println();
System.out
.println("Exam Number Max Score Min Score Average Score");
ps.println("Exam Number Max Score Min Score Average Score");
System.out
.println("-----------------------------------------------------");
ps.println("----------------------------------------------------");
double min = getMin(Ex1);
double max = getMax(Ex1);
double avg = getAvg(Ex1);
System.out.println(String.format("Exam1 %3.1f %3.1f %3.1f", max, min,avg));
ps.println(String.format("Exam1 %3.1f %3.1f %3.1f", max, min,avg));
min = getMin(Ex2);
max = getMax(Ex2);
avg = getAvg(Ex2);
System.out.println(String.format("Exam2 %3.1f %3.1f %3.1f", max, min,avg));
ps.println(String.format("Exam2 %3.1f %3.1f %3.1f", max, min,avg));
min = getMin(Ex3);
max = getMax(Ex3);
avg = getAvg(Ex3);
System.out.println(String.format("Exam3 %3.1f %3.1f %3.1f", max, min,avg));
ps.println(String.format("Exam3 %3.1f %3.1f %3.1f", max, min,avg));
min = getMin(Ex4);
max = getMax(Ex4);
avg = getAvg(Ex4);
System.out.println(String.format("Exam4 %3.1f %3.1f %3.1f", max, min,avg));
ps.println(String.format("Exam4 %3.1f %3.1f %3.1f", max, min,avg));
ps.close();
}
}













Java Program Methods



Java Program for Eclipse



Lab Objectives: To develop ability to write void and value returning methods and to call them
Introduction: Methods are commonly used to break a problem down into small manageable pieces. A large task can be broken down into smaller tasks (methods) that contain the details of how to complete that small task. The larger problem is then solved by implementing the smaller tasks (calling the methods) in the correct order.
This also allows for efficiencies, since the method can be called as many times as needed without rewriting the code each time.
Task #1 void Methods
1.   Type the code (Geometry.java) shown in at the end of this handout. This program will compile, but when you run it, it doesn’t appear to do anything except wait. That is because it is waiting for user input, but the user doesn’t have the menu to choose from yet. We will need to create this.
2.   Above the main method, but in the Geometry class, create a static method called printMenu that has no parameter list and does not return a value. It will simply print out instructions for the user with a menu of options for the user to choose from. The menu should appear to the user as:
This is a geometry calculator
Choose what you would like to calculate
1. Find the area of a circle
2. Find the area of a rectangle
3. Find the area of a triangle
4. Find the circumference of a circle
5. Find the perimeter of a rectangle
6. Find the perimeter of a triangle
Enter the number of your choice:
3.   Add a line in the main method that calls the printMenu method as indicated by the comments.
4.   Compile, debug, and run.  You should be able to choose any option, but you will always get 0 for the answer. We will fix this in the next task.
Task #2 Value-Returning Methods
1.   Write a static method called circleArea that takes in the radius of the circle and returns the area using the formula A = π r 2 .
2.   Write a static method called rectangleArea that takes in the length and width of
the rectangle and returns the area using the formula A = lw.
3.   Write a static method called triangleArea that takes in the base and height of the triangle and returns the area using the formula A = ½bh.
4.   Write a static method called circleCircumference that takes in the radius of the circle and returns the circumference using the formula C = 2πr.
5.   Write a static method called rectanglePerimeter that takes in the length and the width of the rectangle and returns the perimeter of the rectangle using the formula P = 2l +2w.
6.   Write a static method called trianglePerimeter that takes in the lengths of the three sides of the triangle and returns the perimeter of the triangle which is calculated by adding up the three sides.
Task #3 Calling Methods
1.   Add lines in the main method in the Geometry class which will call these methods. The comments indicate where to place the method calls.
2.   Compile, debug, and run.  Test out the program using your sample data.





import java.util.Scanner;
// Demonstration of static methods
public class PutYourClassHere
 {
 public static void main (String [] args)
  {
  int choice; //the user's choice
  double value = 0; //the value returned from the method
  char letter;  //the Y or N from the user's decision to exit 
  double radius; //the radius of the circle
  double length; //the length of the rectangle 
  double width,height;  //the width and height of the rectangle 
  double base;  //the base of the triangle 
  double side1,side2,side3;  // sides of the triangle

//create a scanner object to read from the keyboard
  Scanner keyboard = new Scanner (System.in);

//do loop was chose to allow the menu to be displayed first do
  do
  {
   //call the printMenu method here
   printMenu();
   choice = keyboard.nextInt();

  switch (choice)
  {
   case 1:
    System.out.print("Enter the radius of the circle:  ");
    radius = keyboard.nextDouble();
    value = circleArea(radius);
     //call the circleArea method and store the result in the value 
    System.out.println("The area of the circle is " + value);
    break;
   case 2:
    System.out.print("Enter the length of the rectangle:  "); 
    length = keyboard.nextDouble();
    System.out.print("Enter the width of the rectangle:  ");
    width = keyboard.nextDouble();
    value = rectangleArea(length,width);
    //call the rectangleArea method and store the result in the value 
    System.out.println("The area of the rectangle is " + value); 
    break;
   case 3:
    System.out.print("Enter the height of the triangle:  "); 
    height = keyboard.nextDouble(); 
    System.out.print("Enter the base of the triangle:  "); 
    base = keyboard.nextDouble();
    value = triangleArea(height,base);
    //call the triangleArea method and store the result in the value 
    System.out.println("The area of the triangle is " + value); 
    break;
   case 4:
    System.out.print("Enter the radius of the circle:  ");
    radius = keyboard.nextDouble();
    value = circleCircumference(radius);
    //call the circumference method and store the result in the value 
    System.out.println("The circumference of the circle is " + value); 
    break;
   case 5:
    System.out.print("Enter the length of the rectangle:  "); 
    length = keyboard.nextDouble(); 
    System.out.print("Enter the width of the rectangle:  "); 
    width = keyboard.nextDouble();
    value = rectanglePerimeter(length,width);
    //call the perimeter method and store the result in the value 
    System.out.println("The perimeter of the rectangle is " + value); 
    break;
   case 6:
    System.out.print("Enter the length of side 1 of the triangle:  ");
    side1 = keyboard.nextDouble();
    System.out.print("Enter the length of side 2 of the triangle:  ");
    side2 = keyboard.nextDouble();
    System.out.print("Enter the length of side 3 of the triangle:  ");
    side3 = keyboard.nextDouble();
    value = trianglePerimeter(side1,side2,side3);
    //call the perimeter method and store the result in the value 
    System.out.println("The perimeter of the triangle is " + value); 
    break;
   default:
  System.out.println("You did not enter a valid choice.");
     }//end of switch statement
//consumes the new line character after the number 
  keyboard.nextLine();

  System.out.println("Do you want to exit the program (Y/N)?:  "); 
  String answer = keyboard.nextLine();
  letter = answer.charAt(0); //select first character of response

  }while (letter != 'Y' && letter != 'y'); //end of do-while loop

 }//end of main

//insert your method definitions here
 public static void printMenu() {
  System.out.println("This is a geometry calculator ");
  System.out.println("Choose what you would like to calculate!");
  System.out.println("1. Find the area of a cirlce ");
  System.out.println("2. Find the area of a rectangle ");
  System.out.println("3. Find the area of a triangle ");
  System.out.println("4. Find the circumference of a cirle ");
  System.out.println("5. Find the perimeter of a rectangle ");
  System.out.println("6. Find the perimeter of a triangle");
  System.out.print("Enter the number of your choice: ");
 }
 public static double circleArea(double r) {
  return Math.PI * r * r;
 }
 public static double rectangleArea(double length, double width) {
  return length * width;
 }
 public static double triangleArea(double height, double base) {
  return .5 * height * base;
 }
 public static double circleCircumference(double r) {
  return 2 * Math.PI * r;
 }
 public static double rectanglePerimeter(double length,double width) {
  return 2 * length + 2 * width;
 }
 public static double trianglePerimeter(double side1,double side2, double side3) {
  return side1 + side2 + side3;
 }


}//end of class