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 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 for Switch Statements for the Programming Environment Eclipse



Objective
To 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);

}

 

} 

Programming Project for Eclipse

Assignment

A convenience store sells T-shirt, potato chips, and Coke. The list prices are: $18.95 for T-shirt, $1.79 for a bag of potato chips, and $2.99 for a 12-pack Coke ($1.20 deposit as well). All merchandise except Coke is on sale with 15% off the list price. T-shirt is also charged a 6% Michigan sales tax. A customer shops at the store to buy these items. Write a Java program to simulate the shopping process — interact with the custom and prints a receipt.

Code
import java.util.Scanner;

public class a {

/**
 *
 */
 
public static void main(String[] args) {
 //TODO Audto-generated method stub
 
 
Scanner keyboard = new Scanner(System.in);
 
double shirts = 18.95;
int numOfShirts;
int numOfChips;
int numOfCoke;
double cokeTotal;
double chips = 1.79;
double coke = 2.99;
double subTotal;
double deposit = 1.20;
double preTotal;  
double MItax = 0.06; 
double totalTax; 
double total; 
double payment; 
String name;

//Prompt for the name
System.out.print("What's your name?");
name = keyboard.nextLine();
System.out.println("Welcome to Denny's Market" + name + "! We have the following items for sale:\n");
System.out.println("T-shirt $ " + shirts + " 15% off");
System.out.println("Chips $ " + chips + " 15% off");
System.out.println("Coke $ " + coke + "\n");


//Prompt for number of the shirts 
System.out.println("How many T-shirts do you want?");
numOfShirts = keyboard.nextInt(); 
System.out.println("How many bags of chips would you like?");
numOfChips = keyboard.nextInt();
System.out.println("What about 12-pack Coke?");
numOfCoke = keyboard.nextInt();

//Calculations for the program
cokeTotal = (numOfCoke * deposit) + (numOfCoke * coke);
subTotal = (((shirts * numOfShirts) + (chips * numOfChips) + (coke * numOfCoke) + (deposit * numOfCoke)));
total = (numOfShirts * shirts) *.85 + (numOfChips * chips) *.85 + cokeTotal;
preTotal = (numOfShirts *shirts) + (numOfChips * chips) + cokeTotal;
totalTax = total * MItax; 
total = total + totalTax;

System.out.println("Your total is: $" + total);
System.out.println("Please enter your payment:");
payment = keyboard.nextDouble(); 
System.out.println("\n");

System.out.println(name + ", here is your receipt:");
System.out.println("");
System.out.println("\tItem \tUnit Price \tHow Many \tCost" + "\t");
System.out.println("-----------------------------------------------------------");

System.out.println("\tT-shirt" + "\t" + shirts + "\t" + numOfShirts + "\t" + (shirts * numOfShirts));
System.out.println("\tChips" + "\t" + chips + "\t" + numOfChips + "\t" + (chips * numOfChips)); 
System.out.println("\tCoke" + "\t" + coke + "\t" + numOfCoke + "\t" + (coke * numOfCoke));
System.out.println("\tDeposit" + "\t\t" + "\t" +  + (deposit * numOfCoke));
System.out.println("\n");

System.out.println("\tSubtotal" + "\t\t" + + subTotal);
System.out.println("\tDiscount" + "\t\t" + "-" + (preTotal-total));
System.out.println("\tTax" + "\t\t" + "\t" + + totalTax);
System.out.println("\t" + "\t\t" + "\t" + "---------\n");
System.out.println("\tTotal" + "\t\t" + "\t" + + total + "\n");

//Payment
System.out.println("\tPayment" + "\t\t" + "\t" +  + payment);

//Doing the change
System.out.println("\tYourChange"+ "\t\t" + + ((payment - total)) + "\n");
System.out.println("Than you. Come Again!");
} 

} 

Java Program for Loops in Eclipse.

Java assignment


Problem to Solve

This assignment is to solve problem using loops. Write a program to generate 100 random integers in the range of 0 and 99999, find the frequency count of each digit (0, 1, 2, . . . , 9) in these numbers, and print a frequency histogram.

How to Do It

The Overall program structure may look like this:

  1. Use ten variables for the frequency counts for the ten digits 0, 1, 2, . . . , 9. 
  2. Other variables are also needed. For example, a variable to hold a random number, a variable 
    for the digit, etc. 
  3. Repeat 100 times (a loop): 
    • Generate a random number. 
    • For each digit in the number, increase the frequency count of by 1. This is done 
      using a loop. Note: we do not know how many digits are in the number. 
  4. For each digit from 0 to 9 (a loop): 
    • Store its frequency count into a variable.
    • Display the digit and the frequency count.
    • Display the horizontal frequency bar of asterisks using a loop. 

To accomplish the task, Here are some suggestions:

  1. Generate random integers in the range [0, 99999]. Assume the variable is number
             number = (int)(Math.random() * 99999);
    
  2. Get the digits of the random number. Since we do not know how many digits in the number, you need to use a loop to “peel off” the rightmost digit one at a time using integer division (/) and modulus (%) operations. Here are some example of random numbers and their digits: 

number digits

4028 4028 75 75 66 93540 94540

3. Print a horizontal bar. For each digit (say digit 5) with a frequency count (say 41), a bar is displayed with 41 asterisks like this

         5 (41): *****************************************




The code used for java in Eclipse is


import java.util.Scanner;

public class Enter Your Class Name Here {

/**

* @param args

*/

public static void main(String[] args) {

// TODO Auto-generated method stub

Scanner input = new Scanner(System.in);

//Declare the Variables

int count = 0, count0 = 0, count1 = 0, count2 = 0, count3 = 0, count4 = 0, count5 = 0, count6 = 0, count7 = 0, count8 = 0, count9 = 0; 

int digit1= 1, digit2 = 1, digit3 = 1, digit4 = 1, digit5 = 1;

int num = 1;

//Loop

while (count<100){

num = (int)(Math.random() * 99999); // to generate a random number

count++;

//Break Numbers

digit1 = num / 10;

digit2 = (num % 10000) / 1000;

digit3 = ((num % 10000) % 1000) / 100;

digit4 = (((num % 10000) % 1000) % 100) / 10;

digit5 = ((((num % 10000) % 1000) % 100) % 10);

if(digit1 == 0 || digit2 == 0 || digit3 == 0 || digit4 == 0 || digit5 == 0){

count0 = count0 +1;}

if(digit1 == 1 || digit2 == 1 || digit3 == 1 || digit4 == 1 || digit5 == 1){

count1 = count1 +1;}

if(digit1 == 2 || digit2 == 2 || digit3 == 2 || digit4 == 2 || digit5 == 2){

count2 = count2 +1;}

if(digit1 == 3 || digit2 == 3 || digit3 == 3 || digit4 == 3 || digit5 == 3){

count3 = count3 +1;}

if(digit1 == 4 || digit2 == 4 || digit3 == 4 || digit4 == 4 || digit5 == 4){

count4 = count4 +1;}

if(digit1 == 5 || digit2 == 5 || digit3 == 5 || digit4 == 5 || digit5 == 5){

count5 = count5 +1;}

if(digit1 == 6 || digit2 == 6 || digit3 == 6 || digit4 == 6 || digit5 == 6){

count6 = count6 +1;}

if(digit1 == 7 || digit2 == 7 || digit3 == 7 || digit4 == 7 || digit5 == 7){

count7 = count7 +1;}

if(digit1 == 8 || digit2 == 8 || digit3 == 8 || digit4 == 8 || digit5 == 8){

count8 = count8 +1;}

if(digit1 == 9 || digit2 == 9 || digit3 == 9 || digit4 == 9 || digit5 == 9){

count9 = count9 +1;}

}

System.out.println("\n0" + "(" + count0 + ")");

for (int i = 0; i < count0; i++){

System.out.print("*");}

System.out.println("\n1" + "(" + count1 + ")");

for (int i = 0; i < count1; i++){

System.out.print("*");}

System.out.println("\n2" + "(" + count2 + ")");

for (int i = 0; i < count2; i++){

System.out.print("*");}

System.out.println("\n3" + "(" + count3 + ")");

for (int i = 0; i < count3; i++){

System.out.print("*");}

System.out.println("\n4" + "(" + count4 + ")");

for (int i = 0; i < count4; i++){

System.out.print("*");}

System.out.println("\n5" + "(" + count5 + ")");

for (int i = 0; i < count5; i++){

System.out.print("*");}

System.out.println("\n6" + "(" + count6 + ")");

for (int i = 0; i < count6; i++){

System.out.print("*");}

System.out.println("\n7" + "(" + count7 + ")");

for (int i = 0; i < count7; i++){

System.out.print("*");}

System.out.println("\n8" + "(" + count8 + ")");

for (int i = 0; i < count8; i++){

System.out.print("*");}

System.out.println("\n9" + "(" + count9 + ")");

for (int i = 0; i < count9; i++){

System.out.print("*");}

}

}

 

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 

Java Program Sentinel Control Loop

Use in Program Eclipse


import java.util.Scanner;
public class SentinelControlLoop {

 /**
  * 
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  
  Scanner myInput = new Scanner(System.in);
  
  
  //Declare Variables
  int num, sum = 0, max, min, count =0;
  double average = 0.0;
  final int Sentinel = -9999;
  
  
  //Priming Stage
  System.out.print("Enter an integer value, or -9999 to quit: ");
  num = myInput.nextInt();
  
  //intitalize max and min
  max = min = num;
  
  
  
  //WHILE Loop
  while (num != Sentinel) {
   //body of loop
   //Update Sum
   sum = sum + num; //sum +=
   System.out.println("Sum is now "+ sum);
   
   if (num > max)
    max = num;
   if (num < min)
    min = num;
   
   //increment count of data items read
   count++; //Same as count = count + 1;
   System.out.print("num = " + num + " Count = " + count );
   System.out.print(" Enter an integer value, or -9999 to quit: ");
   num = myInput.nextInt();
   
   
  }
  if (count != 0) {
   average = (double)sum / count;
   System.out.println("Average is " + average);
   System.out.println (" max = "+ max + ", min " + min);
  }
  else 
   System.out.println("Cant average 0 items ");
  
 }
 

} 

This free website was made using Yola.

No HTML skills required. Build your website in minutes.

Go to www.yola.com and sign up today!

Make a free website with Yola