Showing posts with label Cps. Show all posts
Showing posts with label Cps. 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 Switch Statements for Eclipse


Java Program for Switch Statements for the Programming Environment Eclipse



ObjectiveTo learn and practice with multi-way selections using switch statements. Problem Description
Your friend Jackie in Detroit is planning for a vacation. She needs to choose one destination from three possible locations. There are only two approaches for transportation – either drive or fly. If she drives, the gas price is $3.89 per gallon (assume same price across the country) and the average gas mileage of her car is 24 miles per gallon. If she flies, the airfare depends on the destination from Detroit. To Washington DC, she may choose either fly or drive. The meal cost depends on the type of the location: regular ($31 per day) and high-cost ($52 per day).
She will stay at a hotel of her choice at the destination for 3 days. The costs of the hotel rooms are shown below (assume the hotels of the same hotel chain cost the same across the country):
Write a Java program to help Jackie to figure out the cost of the trip (round trip).
Requirements:
  1. Must include a well-written program description to describe the task of the problem. 
  2. Use named constants for the fixed values. 
  3. Display a menu for the user to make a selection. The menu items may be labeled 1, 2, 3, etc. Use switch statements to handle the user’s selection of destination and corresponding transportation method. Assign values to appropriate variables according to user’s selection. Check the validity of user’s inputs using default clause in switch statements. Terminate the execution using System.exit(1); when an invalid input is encountered. 
  4. Do the same for hotel selection. 
  5. Correctly calculate the costs for transportation (round trip), hotel, meals, and the total. 
destination
transportation
airfare
(round trip) 
driving distance
(one way)
meal
Cleveland
drive
169 miles
regular
Las Vegas
fly
$507
high cost
Washington DC 
drive or fly
$328
526 miles
high cost
hotel
cost per day
Comfort Inn 
$85
Marriott
$159
Hyatt
$238
page1image42320

page2image1016
6. The output produced by your program should include itemized costs (i.e. cost of transportation, cost of hotel, and cost of meals) in addition to the total cost, and must be descriptive and well formated.
7. Test your program with various input data, including the minimum of the following:
• Travel to Cleveland, stay at Comfort Inn. • Travel to Las Vegas, stay at Marriott.• Drive to Washington DC, stay at Marriott. • Fly to Washington DC, stay at Hyatt.
• Invalid input.
A sample run may look like this:

Here are the places you may go for vacation.
--------------------------------------------
   1. Cleveland
   2. Las Vegas
   3. Washington DC
--------------------------------------------
Please select the number of the destination --> 3
To Washington DC, do you want to drive (’d’) or fly (’f’)? d
These are the hotels having vacancies:
----------------------------------------
1. Comfort Inn
2. Marriott
3. Hyatt
$ 85.00
$159.00
$238.00
----------------------------------------
Please make your selection --> 2
Cost for your trip:
(drive to Washington DC, staying at Marriott for 3 days):
           ---------------------------
             Trasportation  $ 170.51
             Hotel cost   : $ 477.00
             Cost of meals: $ 156.00
           ---------------------------
             Total cost   : $ 803.51
           ---------------------------
Have a nice vacation!






The Code for this program is 


import java.util.Scanner;
public class Enter Your Class Here{
/**
* @param args
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int destination;
int distance=1;
String dest= "dest";
double transportation;
double airfare, drivingdistance,gallon;
final double regularMeal= 31;
final double highMeal= 52;
double flying, driving;
double gasPrice = 3.89;
final String dest1 = "Cleaveland";
final String dest2 = "Las Vegas";
final String dest3 = "Washington DC";
String hotel0 = "hotel";
final String hotel1= "Comfort Inn ";
final String hotel2= "Marriott";
final String hotel3= "Hyatt";
final double gasMileage = 24.00;
double totaltran = 0 ;
final String cityName;
int hotel=0;
double hotelcost =1;
double mealtotal=0;
int travel =0;
//Users Input
System.out.println(" \t 1 \t \t Cleveland \t");
System.out.println(" \t 2 \t \t Las Vegas \t");
System.out.println(" \t 3 \t \t Washington \t");
System.out.println("Please select the number of the destination?");
destination = input.nextInt();
System.out.println("To" + destination + "do you want to drive ('1') or fly ('2')?");
travel= input.nextInt();
System.out.println("These are the hotels having vacancies:");
System.out.println(" \t 1 \t \t Comfort Inn\t $85.00");
System.out.println(" \t 2 \t \t Marriott \t $159.00");
System.out.println(" \t 3 \t \t Hyatt \t\t $238.00");
System.out.println("Please make your hotels selection");
hotel = input.nextInt();
//Body
switch(destination){
case 1 :dest = dest1;
distance = 169;
totaltran= ((distance = 169*2)/gasMileage)*gasPrice;
mealtotal= regularMeal*3;
break;
case 2 :dest = dest2;
totaltran=507;
mealtotal = highMeal*3;
break;
case 3 : dest = dest3;
mealtotal= highMeal*3;
switch(travel){
case 1: totaltran= ((distance = 526*2)/gasMileage)*gasPrice;
distance = 526;
break;
case 2: totaltran = 328;
break;
}
break;
default:
}
switch(hotel) {
case 1: hotel0=hotel1;
hotelcost = 3 * 85;
break;
case 2: hotel0=hotel2;
hotelcost = 3 * 159;
break;
case 3: hotel0= hotel3;
hotelcost = 3 * 238;
break;
default: System.out.println("hotels doesnt exist");
}
//Calculate and Print Cost 
System.out.println("Cost For Your Trip:");
System.out.println("(Drive to " + dest + ", staying at " + hotel0 + " for 3 days.):");
System.out.println("-----------------------------------------------");
System.out.printf("Transportation $ %4.2f\n" ,totaltran);
System.out.printf("Hotel Cost : $ %4.2f\n" , hotelcost);
System.out.printf("Cost of meals: $ %4.2f\n" , mealtotal);
System.out.println("-----------------------------------------------");
System.out.printf("Total cost : $ %1.2f\n" , totaltran + hotelcost+ mealtotal);
}
}

Java Program Variable Declaration, Numeric Expression, Assignment Statement, Input using Scanner, and Output.


Java Programming for Eclipse

Java basics (variable declaration, numeric expression, assignment statement, input using Scanner, and output).
Problem Description
A person named name purchased numberShares shares of Microsoft stock at the price of buyPrice per share and paid the stockbroker $15 transaction fee. Two weeks later, the person sold the numberShares shares at sellPrice per share and paid another $15 for the transaction. Write a Java program to calculate and display the following:
1. the dollar amount paid for the shares 2. the dollar amount of the shares sold 3. the total transaction fee paid to the broker (including both buy and sale) 4. the amount of profit (or loss) made after selling the shares.
The values of name, numberShares, buyPrice, sellPrice are input from the user. For example, if the interactive execution looks like this (user’s inputs are shown in bold):
What’s your name? Joseph How many shares bought? 250 Buy price? 28.31 Sale price? 30.79



Code for program



import java.util.Scanner;


public class Enter Your Class Here {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub

   Scanner myInput = new Scanner(System.in);
  
  //declare variables
  String name;
     double numberShares, buyPrice, sellPrice, amountPurchase, amountSellPurchase, netProfit, netProfitFinal;
     int transactionFee = 15;
       
     //Prompt
     System.out.print ("What is your name? ");
     name = myInput.nextLine();
     
     System.out.print("How many shares bought? ");
     numberShares =  myInput.nextDouble();
     
     System.out.print("Buy Price? ");
     buyPrice =   myInput.nextDouble();
     
     System.out.print("Sale Price? ");
     sellPrice = myInput.nextDouble();
     
     //calculations
     amountPurchase = numberShares * buyPrice;
     amountSellPurchase = numberShares * sellPrice;
     netProfit = amountSellPurchase - amountPurchase;
     netProfitFinal = netProfit - transactionFee*2;
     
     //Display the resulting information
     System.out.println("Hello " + name + "Here is your information for your stock transaction");
  System.out.println("Number of Shares is " + numberShares);
  System.out.println("Amount of Purchase $" + amountPurchase);
  System.out.println("Amount of sell $" + amountSellPurchase);
  System.out.println("Transaction fee paid $" + transactionFee*2);
  System.out.println("Net Profit: "+ netProfitFinal);
  
  
  
  
 }

}



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