Uploaded by hartwell6

all of the labs

advertisement
Lab One
package weekone;
import java.util.Scanner;
// Needed for the Scanner class
/**
This program calculates the user's gross pay.
*/
public class LabOne {
public static void main(String[] args)
{
// Create a Scanner object to read from the keyboard.
Scanner keyboard = new Scanner(System.in);
// Identifier declarations
double hours; // Number of hours worked
double rate;
// Hourly pay rate
double pay;
// Gross pay
// Display prompts and get input.
System.out.print("How many hours did you work? ");
hours = keyboard.nextDouble();
System.out.print("How much are you paid per hour? ");
rate = keyboard.nextDouble();
// Perform the calculations.
if(hours <= 40)
pay = hours * rate;
else
pay = (hours - 40) * (1.5 * rate) + 40 * rate;
// Display results.
System.out.println("You earned $" + pay);
}
}
import java.util.Scanner;
// Needed for the Scanner class
/**
This program calculates the total price which includes
sales tax.
*/
public class SalesTax {
public static void main(String[] args)
{
// Identifier declarations
final double TAX_RATE = 0.055;
double price;
double tax;
double total;
String item;
//Changes I have made- put ; after double tax
// Create a Scanner object to read from the keyboard.
Scanner keyboard = new Scanner(System.in);
// Display prompts and get input.
System.out.print("Item description:
item = keyboard.nextLine();
System.out.print("Item price: $");
price = keyboard.nextDouble();
");
// Perform the calculations.
tax = price * TAX_RATE;
total = price + tax;
//Changes I made= changed + to * in tax and changed * to + in total also
changed totl to total
// Display the results.
System.out.print(item + "
$");
System.out.println(price);
System.out.print("Tax
$");
System.out.println(tax);
System.out.print("Total
$");
System.out.println(total);
}
}
Lab Two
import java.util.Scanner; //Needed for scanner class
import javax.swing.JOptionPane; // import for Message Pane
//!!!!!!!!!!!!NOTE: Print outs from all tasks are at the very bottom of the
code.!!!!!!!!!!!!!!!!!!!!!
/**
This program demonstrates how numeric types and
operators behave in Java.
*/
public class NumericTypes {
public static void main (String [] args)
{
//TASK #1
// Identifier declarations
final double NUMBER = 2 ;
// Number of scores
final int SCORE1 = 100;
// First test score
final int SCORE2 = 95;
// Second test score
final double BOILING_IN_F = 212; // Boiling temperature
double fToC;
// Temperature Celsius
double average;
// Arithmetic average
String output;
// Line of output
// Create a Scanner object to read from the keyboard.
Scanner sc= new Scanner(System.in);
//TASK #2: IF YOU WERE TO TAKE AWAY THE // COMMENTS IT WOULD
RUN PROPERLY
//TASK #2
// Identifier declarations
//String firstName; // users first name
//String lastName; // users last name
//String fullName; // users first and last
name
//TASK #2 Print Out:
// Display prompts and get input.
//System.out.print("What is your name: ");
//prompts the user for first name
//firstName = sc.nextLine(); //reads the users
first name
//System.out.print("What is your last name:
"); //prompts the user for last name
//lastName = sc.nextLine(); //reads the users
last name
//fullName = firstName + ' ' +lastName; //
Concatenate the user's first and last names
//System.out.println(fullName); //prints out
the users full name
//TASK #2 EXTRA:
//identifier declarations
String first_Name; //users first name
String last_Name; //users last name
String full_name; //the users first and last name combined
// TASK #3 declare variables used here
//identifier declarations
String firstInitial;
String fullName;
// TASK #4 declare variables used here
//identifier declarations
//none availible
//TASK #5 in new file
//PRINT OUTS:
//TASK #1 Print Out:
// Find an arithmetic average.
average = (SCORE1 + SCORE2) / NUMBER; //formula for the average
of the numbers
output = SCORE1 + " and " + SCORE2 +
" have an average of " + average; //so the user knows
what they are reading
System.out.println(output); //prints out the average
// Convert Fahrenheit temperature to Celsius.
fToC = (5.0/9.0) * (BOILING_IN_F - 32); // add .0 to 5 & 9 bc
they are double
output = BOILING_IN_F + " in Fahrenheit is " +
fToC + " in Celsius."; //so the user knows what they
are reading
System.out.println(output); //prints out the farienheit is in
celsius
System.out.println();
// To leave a blank line
//TASK #2 EXTRA PRINT OUT:
//Display prompts and get input
first_Name=JOptionPane.showInputDialog("First Name:
"); //asks the users first name
last_Name=JOptionPane.showInputDialog("Last Name: ");
//asks the users last name
full_name = "You are " + first_Name + " " + last_Name;
//will appear in the dialog box so user knows what they are reading
JOptionPane.showMessageDialog( null, full_name );
//will print out users full name
System.out.println();
// To leave a blank line
//TASK #3 PRINT OUT:
firstInitial = first_Name; //this defines the string
firstInitial from the previous task
char ch = firstInitial.charAt(0); //this will read the first
letter of the users first name
System.out.println("The First Letter of your first name is:
"); //this is so the user knows what is being read
System.out.println(ch); //this will print out the users first
names first letter
System.out.print("Your first name in all caps is: " ); //so the
user knows what is being read
System.out.println(first_Name.toUpperCase() ); //will return
users name in all caps
fullName = first_Name + last_Name; // used to combine the first
and last name
System.out.print("The Length of your full name is: " ); //so the
reader knows what is being read
System.out.println(fullName.length()); //determines the length of
the first name
//TASK #4 PRINT OUT:
Scanner s= new Scanner(System.in);
System.out.println("Enter the radius of sphere: "); // prompts the
reader to enter value of sphere
double r=s.nextDouble();
double volume= (4*22*r*r*r)/(3*7); //volume formula
System.out.println("Volume is:" +volume); //prints the volume
// This program is used to calculate the ammout of miles per gallons used by
the user
/*
* Author: Toby Hartwell
* Date: 9/8/2019
*/
import java.util.Scanner; //needed for scanner class
public class Mileage {
public static void main(String [] args) {
//identifier declarations
double miles; //represents miles of the user
double gallons; //represents gallons used by the user
double totalMiles = 0.0; //represents the total miles by user
double totalGallons = 0.0; //represents the total gallons used by
user
Scanner input = new Scanner(System.in);
System.out.println("\nEnter miles driven or -1 to Quit: "); //allows
user to use an exit if needed
miles = input.nextInt(); // to read the line
while (miles != -1 ) {
//exit if needed
System.out.println("Enter gallons used: "); //prompts the user
to enter amount of gallons
gallons = input.nextInt();//reads it
System.out.println("\nMiles driven for this trip: " + miles);
//user inputs the miles driven
System.out.println("Gallons used for this trip: " + gallons);
//user inputs gallons that were used
totalMiles += miles; //to calculate
totalGallons += gallons; //to calculate
System.out.printf("\nMiles per gallon for this trip:
%f\nCombined Miles "
+ "per gallon: %f\n",(double)miles/gallons,
(double)totalMiles/totalGallons);// to calculate the miles per gallon used
System.out.println("\nEnter miles driven or -1 to Quit: ");
miles = input.nextInt(); //loops back the user to re-enter
information and then combines the old and new amounts
}
System.out.println();
}
Lab 3
import java.util.Scanner;
// scanner needed for code
public class PizzaOrder {
public static void main (String[] args)
{
// Create a Scanner object to read input.
Scanner keyboard = new Scanner (System.in);
//variables used in this program
String firstName;
boolean discount = false;
int inches;
char crustType;
String crust = "Hand-tossed";
double cost = 12.99;
final double TAX_RATE = .08;
double tax;
char choice;
String input;
String toppings = "Cheese ";
int numberOfToppings = 0;
//
//
//
//
//
//
//
//
//
//
//
//
User's first name
Flag for discount
Size of the pizza
For type of crust
Name of crust
Cost of the pizza
Sales tax rate
Amount of tax
User's choice
User input
List of toppings
Number of toppings
// Prompt user and get first name.
System.out.println("Welcome to Mike and " +
"Diane's Pizza"); //Prints at top to let
user know what they are using
System.out.print("Enter your first name: ");
//allows user to input their first name
firstName = keyboard.nextLine();
// ADD LINES HERE FOR TASK #1
// Determine if user is eligible for discount by
// having the same first name as one of the owners.
//here it tells if the user's name is one of the owners Mike or
Diane
//also makes it where case is ignored when comparing
if(firstName.compareToIgnoreCase("Mike")==0||
firstName.compareToIgnoreCase("Diane")==0)
//reads if users name is "Mike" or "Diane" and applies a discount if so.
//set the discount to equal true if above is true
discount=true; //if users name is either Mike or Diane applies the
discount
// Prompt user and get pizza size choice.
//cost & size header
System.out.println("Pizza Size (inches)
Cost");
//10 inch pizza & cost
System.out.println("
10
$10.99");
//12 inch pizza & cost
System.out.println("
12
$12.99");
//14 inch pizza & cost
System.out.println("
14
$14.99");
//16 inch pizza & cost
System.out.println("
16
$16.99");
//displays to ask user what size pizza they want
System.out.println("What size pizza " +
"would you like?");
System.out.print("10, 12, 14, or 16 " +
"(enter the number only): ");
//allows user to input the size pizza the want
inches = keyboard.nextInt(); //reads the input
// Set price and size of pizza ordered.
if(inches==10) //if pizza size is 10, cost 10.99
cost=10.99;
else if(inches==12) //if pizza size is 12, cost 12.99
cost=12.99;
else if(inches==14) //if pizza size is 14, cost 14.99
cost=14.99;
else if(inches==16) //if pizza size is 16, cost 16.99
cost=16.99;
else
{System.out.println(inches+ " is not a valid pizza size, you
will receive"+
"12 inch instead"); //if users input does not match the
indicated numbers, prints out this statement and sets pizza size to 12
inches=12;
cost=12.99;
}
// ADD LINES HERE FOR TASK #2
// Consume the remaining newline character.
keyboard.nextLine();
// Prompt user and get crust choice.
System.out.println("What type of crust " +
"do you want? ");
//lists all of the different types of crust offered
System.out.print("(H)Hand-tossed, " +
"(T) Thin-crust, or " +
"(D) Deep-dish " +
"(enter H, T, or D): ");
input = keyboard.nextLine(); //reads the input
//input character
crustType = input.charAt(0);
// Set user's crust choice on pizza ordered.
// ADD LINES FOR TASK #3
//switch set up for crust type
switch(crustType)
//default is the user will receive hand-tossed if no invalid
input
{default: System.out.println(crustType+ " is not a valid crust,
you will receive"+
"hand-tossed instead");
//reads lower case and upper case h
crustType='h';
case 'H':
case 'h': crust="Hand-tossed";
//break stops the program if this is the choice
break;
//reads lower case and upper case t
case 't':
case 'T': crust="Thin-crust";
//break stops the program if this is the choice
break;
//reads lower case and upper case d
case 'd':
case 'D': crust="Deep-dish";
//break stops the program if this is the choice
break;
}
// Prompt user and get topping choices one at a time.
System.out.println("All pizzas come with cheese.");
//informs user that with extra toppings is extra charge
System.out.println("Additional toppings are " +
"$1.25 each, choose from:");
//lists all different types of toppings
System.out.println("Pepperoni, Sausage, " +
"Onion, Mushroom");
// If topping is desired,
// add to topping list and number of toppings
// asks user if they want pepperoni
System.out.print("Do you want Pepperoni? (Y/N): ");
//allows user input
input = keyboard.nextLine();
//a character input for choice
choice = input.charAt(0);
//reads either lower or upper case
if (choice == 'Y' || choice == 'y')
{
//add +1 toppings if y
numberOfToppings += 1;
toppings = toppings + "Pepperoni ";
}
//asks user if they want sausage
System.out.print("Do you want Sausage? (Y/N): ");
//lets user put input
input = keyboard.nextLine();
//a character input for choice
choice = input.charAt(0);
//reads either lower or upper case
if (choice == 'Y' || choice == 'y')
{
//add +1 to toppings if y
numberOfToppings += 1;
toppings = toppings + "Sausage ";
}
//asks user if they want onion
System.out.print("Do you want Onion? (Y/N): ");
//lets user put input
input = keyboard.nextLine();
//character choice
choice = input.charAt(0);
//reads either lower or upper case
if (choice == 'Y' || choice == 'y')
{
//add +1 to toppings if y
numberOfToppings += 1;
toppings = toppings + "Onion ";
}
System.out.print("Do you want Mushroom? (Y/N): ");
//lets user put input
input = keyboard.nextLine();
//character choice
choice = input.charAt(0);
//reads either lower or upper case
if (choice == 'Y' || choice == 'y')
{
numberOfToppings += 1;
toppings = toppings + "Mushroom ";
}
// Add additional toppings cost to cost of pizza.
cost = cost + (1.25 * numberOfToppings);
// Display order confirmation.
//blank line
System.out.println();
//displays order info
System.out.println("Your order is as follows: ");
//displays inches chose
System.out.println(inches + " inch pizza");
//displays crust chosen
System.out.println(crust + " crust");
//displays toppings chosen
System.out.println(toppings);
// Apply discount if user is eligible.
// ADD LINES FOR TASK #4 HERE
// if discount is true
if(discount)
// will display this message and give $2 off of cost
{System.out.println("You are eligible for a $2 discount");
cost-=2;
}
// EDIT PROGRAM FOR TASK #5
// SO ALL MONEY OUTPUT APPEARS WITH 2 DECIMAL PLACES
//This will display the cost of the users order with two
decimal places
System.out.printf("The cost of your order " +
"is: $%.2f\n", cost);
// Calculate and display tax and total cost.
//Calculates the cost times the tax rate
tax = cost * TAX_RATE;
//displays the tax with two decimal places
System.out.printf("The tax is: $%.2f\n", tax);
//displays the total cost with two decimal places
System.out.printf("The total due is: $%.2f\n",
(tax + cost));
//displays to the user that the order will be ready in 30
minutes
System.out.println("Your order will be ready " +
"for pickup in 30 minutes.");
Lab 4
package weekfour;
//All the imports that are needed to access the files:
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Scanner;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
//TASK #3 Add the file I/O import statement here
/**
This class reads numbers from a file, calculates the
mean and standard deviation, and writes the results
to a file.
*/
public class StatsDemo {
// TASK #3 Add the throws clause
public static void main(String[] args) throws IOException
{
double sum = 0;
// The sum of the numbers
int count = 0;
// The number of numbers added
double mean = 0;
// The average of the numbers
double stdDev = 0;
// The standard deviation
String line;
// To hold a line from the file
double difference;
// The value and mean difference
// Create an object of type Scanner
Scanner keyboard = new Scanner (System.in);
String filename;
// The user input file name
// Prompt the user and read in the file name
System.out.println("This program calculates " +
"statistics on a file " +
"containing a series of numbers");
System.out.print("Enter the file name: ");
filename = keyboard.nextLine();
// ADD LINES FOR TASK #4 HERE
// Create a FileReader object passing it the filename
FileReader fileReader = new
FileReader("C:\\Users\\tobym\\eclipse-workspace\\CS 120\\src");
// Create a BufferedReader object passing FileReader
// object
BufferedReader bufferedReader=new BufferedReader(fileReader);
// Perform a priming read to read the first line of
// the file
line = bufferedReader.readLine();
/// Loop until you are at the end of the file
while(line != null)
{
// Convert the line to a double value and add the
// value to sum
sum = sum + Double.parseDouble(line);
// Increment the counter
count++;
// Read a new line from the file
line= bufferedReader.readLine();
}
// Close the input file
bufferedReader.close();
// Store the calculated mean
mean=sum/count;
// ADD LINES FOR TASK #5 HERE
// Reconnect FileReader object passing it the
// filename
fileReader = new FileReader("C:\\Users\\tobym\\eclipseworkspace\\CS 120\\src");
// Reconnect BufferedReader object passing
// FileReader object
bufferedReader = new BufferedReader(fileReader);
// Reinitialize the sum of the numbers
sum = 0;
// Reinitialize the number of numbers added
count = 0;
// Perform a priming read to read the first line of
// the file
line = bufferedReader.readLine();
// Loop until you are at the end of the file
while(line != null)
{
// Convert the line into a double value and
// subtract the mean
difference =Double.parseDouble(line) - mean;
// Add the square of the difference to the sum
sum = sum + difference*difference;
// Increment the counter
count++;
// Read a new line from the file
line=bufferedReader.readLine();
}
// Close the input file
bufferedReader.close();
// Store the calculated standard deviation
stdDev = Math.sqrt(sum/count);
// ADD LINES FOR TASK #3 HERE
// Create a FileWriter object using "Results.txt"
FileWriter file=new FileWriter("Results.txt");
// Create a PrintWriter object passing the
// FileWriter object
PrintWriter outputFile = new PrintWriter(file);
// Print the results to the output file and round three
decimal places
outputFile.printf("standard deviation = %.3f,",stdDev);
//Print on the Next Line
outputFile.println();
//Round to Three Decimal Places
outputFile.printf("mean = %.3f.",mean);
// Close the output file
outputFile.close();
}
}
import java.util.Random; // Needed for the Random class
/**
This class simulates rolling a pair of dice 10,000 times
and counts the number of times doubles of are rolled for
each different pair of doubles.
*/
public class DiceSimulationForLoop { public static void main(String[] args)
{
final int NUMBER = 10000; // Number of dice rolls
// A random number generator used in
// simulating the rolling of dice
Random generator = new Random(); //needed so it randomly rolls the
die
int die1Value; // Value of the first die
int die2Value; // Value of the second die
int count = 0; // Total number of dice rolls
int snakeEyes = 0; // Number of snake eyes rolls
int twos = 0; // Number of double two rolls
int threes = 0; // Number of double three rolls
int fours = 0; // Number of double four rolls
int fives = 0; // Number of double five rolls
int sixes = 0; // Number of double six rolls
// TASK #1 Enter your code for the algorithm here
/*Repeat while the number of dice rolls are less than the number of
times the dice should
be rolled.
*/
//Get the value of the first die by “rolling” the first die
//Get the value of the second die by “rolling” the second die
for (count=0; count < NUMBER; count++) //allows the number of the
times the die is rolled to be less that 10000
{
die1Value = generator.nextInt(6)+1; // Lets dice values be
for 1-6 and not 0
die2Value = generator.nextInt(6)+1;// Lets dice values be for
1-6 and not 0
if (die1Value == die2Value) //sets dice value one equal to
dice value two
{
if (die1Value == 1) //if dice1value is rolled a one
{snakeEyes++;} //increases the number of times snake
eyes were rolled
else if (die1Value == 2) //if dice1value is rolled a
two
{twos++;} //increases the number of times twos were
rolled
else if (die1Value == 3) //if dice1value is rolled a
three
{threes++;} //increases the number of times threes
were rolled
else if (die1Value == 4) //if dice1value is rolled a
four
{fours++;} //increases the number of times fours were
rolled
else if (die1Value == 5) //if dice1value is rolled a
five
{fives++;} //increases the number of times fives were
rolled
else if (die1Value == 6) //if dice1value is rolled a
six
{sixes++;} //increases the number of times sixes were
rolled
}
}
// Display the results
System.out.println ("You rolled snake eyes " +
snakeEyes + " out of " +
count + " rolls.");
System.out.println ("You rolled double twos " +
twos + " out of " + count +
" rolls.");
System.out.println ("You rolled double threes " +
threes + " out of " + count +
" rolls.");
System.out.println ("You rolled double fours " +
fours + " out of " + count +
" rolls.");
System.out.println ("You rolled double fives " +
fives + " out of " + count +
" rolls.");
System.out.println ("You rolled double sixes " +
sixes + " out of " + count +
" rolls.");
}
}
import java.util.Random; // Needed for the Random class
/**
This class simulates rolling a pair of dice 10,000 times
and counts the number of times doubles of are rolled for
each different pair of doubles.
*/
public class DiceSimulationDoWhile {
public static void main(String[] args)
{
final int NUMBER = 10000; // Number of dice rolls
// A random number generator used in
// simulating the rolling of dice
Random generator = new Random(); //needed so it randomly
rolls the die
int die1Value; // Value of the first die
int die2Value; // Value of the second die
int count = 0; // Total number of dice rolls
int snakeEyes = 0; // Number of snake eyes rolls
int twos = 0; // Number of double two rolls
int threes = 0; // Number of double three rolls
int fours = 0; // Number of double four rolls
int fives = 0; // Number of double five rolls
int sixes = 0; // Number of double six rolls
// TASK #1 Enter your code for the algorithm here
/*Repeat while the number of dice rolls are less than the
number of times the dice should
be rolled.
*/
//Get the value of the first die by “rolling” the first die
//Get the value of the second die by “rolling” the second die
do
{
die1Value = generator.nextInt(6)+1; // Lets dice
values be for 1-6 and not 0
die2Value = generator.nextInt(6)+1;// Lets dice values
be for 1-6 and not 0
if (die1Value == die2Value) //sets dice value one
equal to dice value two
{
if (die1Value == 1) //if dice1value is rolled
a one
{snakeEyes++;} //increases the number of times
snake eyes were rolled
else if (die1Value == 2) //if dice1value is
rolled a two
{twos++;} //increases the number of times twos
were rolled
else if (die1Value == 3) //if dice1value is
rolled a three
{threes++;} //increases the number of times
threes were rolled
else if (die1Value == 4) //if dice1value is
rolled a four
{fours++;} //increases the number of times
fours were rolled
else if (die1Value == 5) //if dice1value is
rolled a five
{fives++;} //increases the number of times
fives were rolled
else if (die1Value == 6) //if dice1value is
rolled a six
{sixes++;} //increases the number of times
sixes were rolled
}
count++; //increases the number of times the dice were
rolled
}
while(count < NUMBER); //allows the number of the times the
die is rolled to be less that 10000
// Display the results
System.out.println ("You rolled snake eyes " +
snakeEyes + " out of " +
count + " rolls.");
System.out.println ("You rolled double twos " +
twos + " out of " + count +
" rolls.");
System.out.println ("You rolled double threes " +
threes + " out of " + count +
" rolls.");
System.out.println ("You rolled double fours " +
fours + " out of " + count +
" rolls.");
System.out.println ("You rolled double fives " +
fives + " out of " + count +
" rolls.");
System.out.println ("You rolled double sixes " +
sixes + " out of " + count +
" rolls.");
}
}
package weekfour;
import java.util.Random; // Needed for the Random class
/**
This class simulates rolling a pair of dice 10,000 times
and counts the number of times doubles of are rolled for
each different pair of doubles.
*/
public class DiceSimulation {
public static void main(String[] args)
{
final int NUMBER = 10000; // Number of dice rolls
// A random number generator used in
// simulating the rolling of dice
Random generator = new Random(); //needed so it randomly
rolls the die
int die1Value; // Value of the first die
int die2Value; // Value of the second die
int count = 0; // Total number of dice rolls
int snakeEyes = 0; // Number of snake eyes rolls
int twos = 0; // Number of double two rolls
int threes = 0; // Number of double three rolls
int fours = 0; // Number of double four rolls
int fives = 0; // Number of double five rolls
int sixes = 0; // Number of double six rolls
// TASK #1 Enter your code for the algorithm here
/*Repeat while the number of dice rolls are less than the
number of times the dice should
be rolled.
*/
//Get the value of the first die by “rolling” the first die
//Get the value of the second die by “rolling” the second die
while(count < NUMBER) //allows the number of the times the
die is rolled to be less that 10000
{
die1Value = generator.nextInt(6)+1; // Lets dice
values be for 1-6 and not 0
die2Value = generator.nextInt(6)+1; // Lets dice
values be for 1-6 and not 0
if (die1Value == die2Value) //sets dice value one
equal to dice value two
{
if (die1Value == 1) //if dice1value is rolled
a one
{snakeEyes++;} //increases the number of times
snake eyes were rolled
else if (die1Value == 2) //if dice1value is
rolled a two
{twos++;} //increases the number of times twos
were rolled
else if (die1Value == 3) //if dice1value is
rolled a three
{threes++;} //increases the number of times
threes were rolled
else if (die1Value == 4) //if dice1value is
rolled a four
{fours++;} //increases the number of times
fours were rolled
else if (die1Value == 5) //if dice1value is
rolled a five
{fives++;} //increases the number of times
fives were rolled
else if (die1Value == 6) //if dice1value is
rolled a six
{sixes++;} //increases the number of times
sixes were rolled
}
count++; //increases the number of times the dice were
rolled
}
// Display the results
System.out.println ("You rolled snake eyes " +
snakeEyes + " out of " +
count + " rolls.");
System.out.println ("You rolled double twos " +
twos + " out of " + count +
" rolls.");
System.out.println ("You rolled double threes " +
threes + " out of " + count +
" rolls.");
System.out.println ("You rolled double fours " +
fours + " out of " + count +
" rolls.");
System.out.println ("You rolled double fives " +
fives + " out of " + count +
" rolls.");
System.out.println ("You rolled double sixes " +
sixes + " out of " + count +
" rolls.");
}
Lab 5
package weekfive;
import java.util.Scanner;
/**
* This program demostrates static methods
* @author tobym
*
*/
public class Geometry {
/**
* This is a class that will ask
to calculate
* @param args
*/
public static void main(String[]
{
int choice;
// The
double value = 0; // The
char letter;
// The
double radius;
// The
double length;
// The
double width;
// The
double height;
// The
double base;
// The
double side1;
// The
double side2;
// The
double side3;
// The
user what geometry they would like
args)
user's choice
method's return value
user's Y or N decision
radius of the circle
length of the rectangle
width of the rectangle
height of the triangle
base of the triangle
first side of the triangle
second side of the triangle
third side of the triangle
// Create a scanner object to read from the keyboard
Scanner keyboard = new Scanner(System.in);
// The do loop allows the menu to be displayed first
do
{
// TASK #1 Call the printMenu method
/**
* This calls the printMenu
*/
printMenu();
choice = keyboard.nextInt();
switch(choice)
{
case 1:
System.out.print("Enter the radius of " +
"the circle: ");
radius = keyboard.nextDouble();
// TASK #3 Call the circleArea method and
// store the result in the value variable
/**
* This calls the circleArea equation to be
used
*/
value = circleArea(radius);
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();
// TASK #3 Call the rectangleArea method and
// store the result in the value variable
/**
* This calls the rectangleArea equation to be
used
*/
value=rectangleArea(length,width);
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();
// TASK #3 Call the triangleArea method and
// store the result in the value variable
/**
* This calls the triangleArea equation to be
used
*/
value=triangleArea(base,height);
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();
// TASK #3 Call the circumference method and
// store the result in the value variable
/**
* This calls the circleCircumferene equation
to be used
*/
value=circleCircumference(radius);
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();
// TASK #3 Call the perimeter method and
// store the result in the value variable
/**
* This calls the rectanglePerimeter equation
to be used
*/
value=rectanglePerimeter(length,width);
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();
// TASK #3 Call the perimeter method and
// store the result in the value variable
/**
* This calls the trianglePerimeter equation
to be used
*/
value=trianglePerimeter(side1,side2,side3);
System.out.println("The perimeter of " +
"the triangle is " +
value);
break;
default:
System.out.println("You did not enter " +
"a valid choice.");
}
keyboard.nextLine(); // Consume the new line
System.out.println("Do you want to exit " +
"the program (Y/N)?: ");
String answer = keyboard.nextLine();
letter = answer.charAt(0);
} while(letter != 'Y' && letter != 'y');
// Task 3 Extra: How you can be sure that user can enter
double number but not String or Character?
// Task 3 Extra: How you can be sure that the given side
values for Triangle can form a Triangle? Can sideOne = 1, sideTwo = 2, and
sideThree = 3 be a Triangle?
}
// TASK #1 Create the printMenu method 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 circle" );
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 circle");
System.out.println("5. Find the perimeter of a rectangle");
System.out.println("6. Find the perimeter of a triangle");
System.out.println("Enter the number of your choice: ");
}
// TASK #2 Create the value-returning methods here
/**
* This will calculate the area of the circle
* @param r -radius
* @return area of the circle
*/
public static double circleArea(double r)
{return Math.PI*(r*r);
}
/**
* This will calculate the area of the rectangle
* @param l -length
* @param w -width
* @return area of the rectangle
*/
public static double rectangleArea(double l,double w)
{return l*w;
}
/**
* This will calculate area of a triangle
* @param base
* @param height
* @return area of a triangle
*/
public static double triangleArea(double base,double height)
{return 1/2.*(base*height);
}
/**
* This will calculate a circles circumference
* @param r -radius
* @return circle circumference
*/
public static double circleCircumference(double r)
{return 2.*Math.PI*r;
}
/**
* This will calculate the perimeter of a triangle
* @param side1
* @param side2
* @param side3
* @return perimeter of triangle
*/
public static double trianglePerimeter(double side1,double
side2,double side3)
{return side1+side2+side3;
}
/**
* This will calculate the perimeter of a rectangle
* @param l -length
* @param w -width
* @return rectangle perimeter
*/
public static double rectanglePerimeter(double l,double w)
{return 2*l+2*w;
}
// TASK #4 Write javadoc comments for each method}
Lab 6
package weeksix;
import java.util.Scanner; // Needed for the Scanner class
/**
* This class demonstrates the Television class
* The purpose of this class is to model a television
* Date: 10/3/2019
* @author tobyhartwell
*
*/
public class TelevisionDemo {
/**
*
* @param args
*/
public static void main(String[] args)
{
// Create a Scanner object to read from the keyboard
Scanner keyboard = new Scanner (System.in);
// Declare variables
int station;
// The user's channel choice
// Declare and instantiate a television object
Television bigScreen = new Television("Toshiba", 55);
// Turn the power on
bigScreen.power();
// Display the state of the television
System.out.println("A " +
bigScreen.getSCREEN_SIZE() +
" inch " +
bigScreen.getManufacturer() +
" has been turned on.");
// Prompt the user for input and store into station
System.out.print("What channel do you want? ");
station = keyboard.nextInt(); //reads the users input
// Change the channel on the television
bigScreen.setChannel(station);
// Increase the volume of the television
bigScreen.increaseVolume();
// Display the the current channel and
// volume of the television
System.out.println("Channel: " +
bigScreen.getChannel() +
" Volume: " +
bigScreen.getVolume());
System.out.println("Too loud! Lowering the volume.");
// Decrease the volume of the television
bigScreen.decreaseVolume();
bigScreen.decreaseVolume();
bigScreen.decreaseVolume();
bigScreen.decreaseVolume();
bigScreen.decreaseVolume();
bigScreen.decreaseVolume();
// Display the the current channel and
// volume of the television
System.out.println("Channel: " +
bigScreen.getChannel() +
" Volume: " +
bigScreen.getVolume());
System.out.println();
// For a blank line
// HERE IS WHERE YOU DO TASK #5
// Declare and instantiate a television object
Television television = new Television ("Sharp", 19);
// turn the power on
television.power();
// Display the state of the television
System.out.println("A " + television.getSCREEN_SIZE() +
" inch " +
television.getManufacturer() +
" has been turned on.");
//decrease the volume of the television
television.decreaseVolume();
television.decreaseVolume();
//ask user what channel they would like to turn to
System.out.println("What channel would you like? ");
station = keyboard.nextInt(); //reads the users input
//change the channel of the television
television.setChannel(station);
// Display the the current channel and
// volume of the television
System.out.println("Channel: " + television.getChannel() + "
Volume: "
+ television.getVolume());
}
}
package weeksix;
/* This is a public class for the television demo
* it will
* @author Toby Hartwell
*/
public class Television {
private final String MANUFACTURER; //For the manufacturer of the
television
private final int SCREEN_SIZE; //For the size of the television
private boolean powerOn = false; //powerOn is boolean to determine
whether the tv is on or off
private int channel; //to receive the channel of the television
private int volume; //to receive the volume of the television
/**
*
* @param manufacturer to see what the television manufacturer is
* @param SCREEN_SIZE to see what the television screen size is
*/
public Television (String manufacturer, int SCREEN_SIZE) {
//TODO AUTO GENERATED CONSTRUCTOR STUB
this.MANUFACTURER = manufacturer; //for the manufacturer of
the television
this.SCREEN_SIZE = SCREEN_SIZE; //for the screen size of the
television
volume = 20; //default volume of the television
channel = 2; //default channel of the television
SCREEN_SIZE = 55; //default screen size
}
/**
*
* @return the powerOn
*/
public boolean isPowerOn() {
return powerOn; //to determine if the television is on or off
}
/**
*
* @param powerOn sets the power to on
*/
public void setPowerOn(boolean powerOn) {
this.powerOn = powerOn; //sets the television to on
}
/**
*
* @return the channel
*/
public int getChannel() {
return channel; //to get the channel of the television
}
/**
*
* @param channel sets the channel to an integer so user can insert
integer
*/
public void setChannel(int channel) {
this.channel = channel;
}
/**
*
* @return gets the volume of the television
*/
public int getVolume() {
return volume; //receives the volume of the television
}
/**
*
* @return receives and returns the manufacturer of the television
*/
public String getManufacturer() {
return MANUFACTURER; //receives the manufacturer of the
television
}
/**
*
* @return recieves and returns the size of the television
*/
public int getSCREEN_SIZE() {
return SCREEN_SIZE; //receives the screen size of the
television
}
public void increaseVolume() {
//This will stop it from being turned up if already at 25
if(volume != 25) {
volume++; //if the volume is not 100 increases the
volume of the television
}
}
public void decreaseVolume() {
if (volume != 0) {
volume--; //if the volume of the television is not
equal to 0, decreases the volume
}
}
public void power() {
//turns the television on
powerOn = !powerOn;
}
}
Lab 7
package weekseven;
/*
This class stores data about a song.
*/
public class Song
{
private String title;
private String artist;
// The song's title
// The song's artist
/**
Constructor
@param title A reference to a String object
containing the song's title.
@param artist A reference to a String object
containing the song's artist.
*/
public Song(String title, String artist)
{
this.title = title; //for the title
this.artist = artist; //for the artist
}
/**
The toString method
@return A String object containing the name
of the song and the artist.
*/
public String toString()
{
return title + " by " + artist + "\n"; //returns the title
and artist
}
import java.io.*;
/**
This program creates a list of songs for a CD
by reading from a file.
*/
public class CompactDisc
{
/**
*
* @param args
* @throws IOException
*/
public static void main(String[] args)throws IOException
{
FileReader file = new
FileReader("C:\\Users\\tobym\\OneDrive\\Documents\\Classics.txt");
BufferedReader input = new BufferedReader(file);
String title; //for the song title
String artist; //for the song artist
Song[] cd = new Song[6];
// ADD LINES FOR TASK #3 HERE
// Declare an array of Song objects, called cd,
// with a size of 6
for (int i = 0; i < cd.length; i++)
{
title = input.readLine();
artist = input.readLine();
//
//
//
//
ADD LINES FOR TASK #3 HERE
Fill the array by creating a new song with
the title and artist and storing it in the
appropriate position in the array
cd[i]= new Song(title, artist);
}
System.out.println("Contents of Classics:");
for (int i = 0; i < cd.length; i++)
{
// ADD LINES FOR TASK #3 HERE
// Print the contents of the array to the console
System.out.println(cd[i]); //to print the cd list
}
package weekseven;
public class AverageDriver
{
/**
*
* @param s
*/
public static void main(String s[])
{
Average a= new Average();
System.out.println(a);
}
}
package weekseven;
import java.util.*; //for the scanner
/**
*
* @author tobym
*
*/
public class Average {
int[] data; //for the data
double mean; //for the calculation of the mean
Average()
{
Scanner s= new Scanner(System.in); //scanner needed
data= new int[5]; //a
System.out.println("Enter Integers ");
for(int i=0;i<5;i++) //to restrain
{
data[i]=s.nextInt(); //the array which will contain
the scores
}
}
public void selectionSort() //this method uses the selection sort
algorithm to rearrange the data set from highest to lowest
{
int temp;
for(int i=0;i<data.length;i++)
for(int j=i+1;j<data.length;j++)
{
if(data[i]<data[j])
{
temp=data[i];
data[i]=data[j];
data[j]=temp;
}
}
}
public double calculateMean() //the arithmetic average of the scores
{
double sum=0;
for(int i=0;i<data.length;i++)
{
sum=sum+data[i]; //for the sum for the mean
}
return sum/data.length; //returns the sum
}
public String toString() //returns a String containing data in
descending order and the mean
{
String s="";
selectionSort();
for(int i=0;i<data.length;i++)
{
s=s+data[i]+" ";
}
s=s+"\nMean: "+calculateMean(); //calculates the mean
return s; //returns the string
Lab 8
/**
* @author tobyhartwell
This class defines a person by name and address.
*/
public class Person {
// The person's last name
private String lastName;
// The person's first name
private String firstName;
// The person's address
private Address home;
/**
Constructor
@param last The person's last name.
@param first The person's first name.
@param residence The person's address.
*/
public Person(String last, String first,
Address residence)
{
lastName = last;
firstName = first;
home = residence;
}
/**
The toString method
@return Information about the person.
*/
public String toString()
{
return(firstName + " " + lastName +
", " + home.toString());
/**
* @author tobyhartwell
This program demonstrates the Money class.
*/
public class MoneyDemo {
public static void main(String[] args)
{
// Named constants
final int BEGINNING = 500; // Beginning balance
final Money FIRST_AMOUNT = new Money(10.02);
final Money SECOND_AMOUNT = new Money(10.02);
final Money THIRD_AMOUNT = new Money(10.88);
// Create an instance of the Money class with
// the beginning balance.
Money balance = new Money(BEGINNING);
// Display the current balance.
System.out.println("The current amount is " +
balance.toString());
// Add the second amount to the balance
// and display the results.
balance = balance.add(SECOND_AMOUNT);
System.out.println("Adding " + SECOND_AMOUNT +
" gives " + balance.toString());
// Subtract the third amount from the balance
// and display the results.
balance = balance.subtract(THIRD_AMOUNT);
System.out.println("Subtracting " + THIRD_AMOUNT +
" gives " + balance.toString());
// Determine if the second amount equals
// the first amount and store the result.
boolean equal = SECOND_AMOUNT.equals(FIRST_AMOUNT);
// Display the result.
if(equal)
{
// The first and second amounts are equal.
System.out.println(SECOND_AMOUNT + " equals " +
FIRST_AMOUNT);
}
else
{
// The first and second amounts are not equal.
System.out.println(SECOND_AMOUNT +
" does not equal " +
FIRST_AMOUNT);
}
// Determine if the third amount equals
// the first amount and store the result.
equal = THIRD_AMOUNT.equals(FIRST_AMOUNT);
// Display the result.
if(equal)
{
// The third and first amounts are equal.
System.out.println(THIRD_AMOUNT + " equals " +
FIRST_AMOUNT);
}
else
{
// The third and first amounts are not equal.
System.out.println(THIRD_AMOUNT +
" does not equal " +
FIRST_AMOUNT);
}
/**
* @author tobyhartwell
This class represents nonnegative amounts of money.
*/
public class Money {
// The number of dollars
private long dollars;
// The number of cents
private long cents;
/**
Constructor
@param amount The amount in decimal format.
*/
public Money(double amount)
{
if (amount < 0)
{
System.out.println("Error: Negative amounts " +
"of money are not allowed.");
System.exit(0);
}
else
{
long allCents = Math.round(amount * 100);
dollars = allCents / 100;
cents = allCents % 100;
}
}
// ADD LINES FOR TASK #1 HERE
// Document and write a copy constructor
public Money(Money money) {
//TODO Auto-generated constructor sub
this.dollars=money.dollars;
this.cents=money.cents;
}
/**
The add method
@param otherAmount The amount of money to add.
@return The sum of the calling Money object
and the parameter Money object.
*/
public Money add(Money otherAmount)
{
Money sum = new Money(0);
sum.cents = this.cents + otherAmount.cents;
long carryDollars = sum.cents / 100;
sum.cents = sum.cents % 100;
sum.dollars = this.dollars +
otherAmount.dollars +
carryDollars;
return sum;
}
/**
The subtract method
@param amount The amount of money to subtract.
@return The difference between the calling Money
object and the parameter Money object.
*/
public Money subtract (Money amount)
{
Money difference = new Money(0);
if (this.cents < amount.cents)
{
this.dollars = this.dollars - 1;
this.cents = this.cents + 100;
}
difference.dollars = this.dollars - amount.dollars;
difference.cents = this.cents - amount.cents;
return difference;
}
/**
The compareTo method
@param amount The amount of money to compare against.
@return -1 if the dollars and the cents of the
calling object are less than the dollars and
the cents of the parameter object.
0 if the dollars and the cents of the calling
object are equal to the dollars and cents of
the parameter object.
1 if the dollars and the cents of the calling
object are more than the dollars and the
cents of the parameter object.
*/
public int compareTo(Money amount)
{
int value;
if(this.dollars < amount.dollars)
value = -1;
else if (this.dollars > amount.dollars)
value = 1;
else if (this.cents < amount.cents)
value = -1;
else if (this.cents > amount.cents)
value = 1;
else
value = 0;
return value;
}
// ADD LINES FOR TASK #2 HERE
// Document and write an equals method
@Override
public boolean equals(Object o) {
Money money = (Money) o;
if(dollars!= money.dollars) return false;
return cents == money.cents;
}
// Document and write a toString method
public String toString() {
return "$"+dollars+"."+(cents<10? "0"+cents : cents);
}
/**
* @author tobyhartwell
This program demonstrates the CreditCard class.
*/
public class CreditCardDemo
{
public static void main(String[] args)
{
//Named constants
final Money CREDIT_LIMIT = new Money(1000);
final Money FIRST_AMOUNT = new Money(200);
final Money SECOND_AMOUNT = new Money(10.02);
final Money THIRD_AMOUNT = new Money(25);
final Money FOURTH_AMOUNT = new Money(990);
//Create an instance of the Person class.
Person owner = new Person("Christie", "Diane",
new Address("237J Harvey Hall",
"Menomonie", "WI", "54751"));
//Create an instance of the CreditCard class.
CreditCard visa = new CreditCard(owner,
CREDIT_LIMIT);
//Display the credit card information.
System.out.println(visa.getPersonals());
System.out.println("Balance: " + visa.getBalance());
System.out.println("Credit Limit: " +
visa.getCreditLimit());
System.out.println(); // To print a new line
//Attempt to charge the first amount and
//display the results.
System.out.println("Attempting to charge " +
FIRST_AMOUNT);
System.out.println("Charge: " + FIRST_AMOUNT);
visa.charge(FIRST_AMOUNT);
System.out.println("Balance: " + visa.getBalance());
System.out.println(); // To print a new line
//Attempt to charge the second amount and
//display the results.
System.out.println("Attempting to charge " +
SECOND_AMOUNT);
System.out.println("Charge: " + SECOND_AMOUNT);
visa.charge(SECOND_AMOUNT);
System.out.println("Balance: " + visa.getBalance());
System.out.println(); // To print a new line
//Attempt to pay using the third amount and
//display the results.
System.out.println("Attempting to pay " +
THIRD_AMOUNT);
System.out.println("Charge: " + THIRD_AMOUNT);
visa.payment(THIRD_AMOUNT);
System.out.println("Balance: " + visa.getBalance());
System.out.println(); // To print a new line
//Attempt to charge using the fourth amount and
//display the results.
System.out.println("Attempting to charge " +
FOURTH_AMOUNT);
System.out.println("Charge: " + FOURTH_AMOUNT);
visa.charge(FOURTH_AMOUNT);
System.out.println("Balance: " + visa.getBalance());
}
/**
* credit card class to reference the person, initialize the owner
* and reference to a money object
* @author tobyhartwell
*
*/
public class CreditCard {
private Person owner; //for the owner of the credit card
private Money balance; //for the balance of the credit card
private Money creditLimit; //for the credit lime of the credit card
/**
*
* @param owner of the credit card
* @param creditLimit of the credit card
*/
//constructor with two parameters
//reference to person object
//reference to money object
public CreditCard(Person owner, Money creditLimit)
{
this.owner = owner;
this.balance = new Money(0);
this.creditLimit = new Money(creditLimit);
}
/**
*
* @return
*/
//accessor method to get balance and creditLimit
public String getCreditLimit()
{
Money limit = new Money(this.creditLimit);
return limit.toString();
}
/**
*
* @return
*/
//accessor method to get info about the ownder
public String getPersonals()
{
return this.owner.toString();
}
/**
*
* @param money
*/
//method to charge the CreditCard
//does not exceed CreditCard limit
//error message will print if creditlimit is exceeded
public void charge(Money money)
{
int state =
(money.add(this.balance)).compareTo(this.creditLimit);
if (state == -1) {
this.balance = this.balance.add(money);
} else
System.out.println("Exceeds credit limit!");
}
/**
*
* @param money
*/
//method to make a payment on the CreditCard
//by subtracting the amount passed in the parameter from the balance
public void payment(Money money)
{
this.balance = this.balance.subtract(money);
}
/**
*
* @return
*/
//gets the balance of the creditcard
public String getBalance() {
Money ret = new Money(this.balance);
return ret.toString();
}
/**
* @author tobyhartwell
This class defines an address using a street,
city, state, and zipcode.
*/
public class Address {
// The street number and name
private String street;
// The city in which the address is located
private String city;
// The state in which the address is located
private String state;
// The zip code associated with the city and street
private String zip;
/**
Constructor
@param road Describes the street number and name.
@param town Describes the city.
@param st Describes the state.
@param zipCode Describes the zip code.
*/
public Address(String road, String town, String st,
String zipCode)
{
street = road;
city = town;
state = st;
zip = zipCode;
}
/**
The toString method
@return Information about the address.
*/
public String toString()
{
return (street + ", " + city +
", " + state + " " + zip);
}
Download