This document provides hints and instructions for completing several exercises from the Java How to Program textbook. It includes hints for exercises on creating a grade book program, calculating sums with loops, a gas mileage calculator, and a mortgage calculator. The hints describe modifications needed to existing code, such as adding parameters to constructors, incrementing counters in loops, and creating separate classes for programs and tests.
MCRL2 by kashif khan
kashif.namal@gmail.com
Master in Computer Science University of Camerino italy
Bachelor in Software Engineering University of Bradford UK
ReactOS is intensively developing, and its codebase is steadily growing in size. On February 16, 2016, a new version of the operating system was released, and we thought it was a good occasion to run it through our static analyzer one more time. The new scan was done with PVS-Studio, version 6.02.
A storage class defines the scope (visibility) and life time of variables and/or functions within a C++ Program. There are following storage classes which can be used in a C++ Program
auto
register
static
extern
MCRL2 by kashif khan
kashif.namal@gmail.com
Master in Computer Science University of Camerino italy
Bachelor in Software Engineering University of Bradford UK
ReactOS is intensively developing, and its codebase is steadily growing in size. On February 16, 2016, a new version of the operating system was released, and we thought it was a good occasion to run it through our static analyzer one more time. The new scan was done with PVS-Studio, version 6.02.
A storage class defines the scope (visibility) and life time of variables and/or functions within a C++ Program. There are following storage classes which can be used in a C++ Program
auto
register
static
extern
Python Training in Bangalore | Python Introduction Session | LearnbayLearnbayin
Python Introduction:
Python is an example of a high-level language.
Python is considered an interpreted language because Python programs are executed by an interpreter.
An Interpreter processes the program a little at a time.
It is about c++ loop controlling statements which include for loop, while loop, do-while loop etc. The examples given has tried to clarify the iteration and how the loop works. Have a nice reading... Enjoy it. Feel free to contact me please.
Functional Programming in Java - Code for MaintainabilityMarcin Stepien
Functional Programming is nothing new to the JVM. But with Java 8 it was the big change in paradigm for Java developers. Learn how switching from imperative to functional results in more maintainable code.
The presentation was given at tech meetup KrkDataLink, The missing link between Functional Programming and Data Science.
what are loop in general
what is loop in c language
uses of loop in c language
types of loop in c language
program of loop in c language
syantax of loop in c language
Python Training in Bangalore | Python Introduction Session | LearnbayLearnbayin
Python Introduction:
Python is an example of a high-level language.
Python is considered an interpreted language because Python programs are executed by an interpreter.
An Interpreter processes the program a little at a time.
It is about c++ loop controlling statements which include for loop, while loop, do-while loop etc. The examples given has tried to clarify the iteration and how the loop works. Have a nice reading... Enjoy it. Feel free to contact me please.
Functional Programming in Java - Code for MaintainabilityMarcin Stepien
Functional Programming is nothing new to the JVM. But with Java 8 it was the big change in paradigm for Java developers. Learn how switching from imperative to functional results in more maintainable code.
The presentation was given at tech meetup KrkDataLink, The missing link between Functional Programming and Data Science.
what are loop in general
what is loop in c language
uses of loop in c language
types of loop in c language
program of loop in c language
syantax of loop in c language
week3_src/DoWhileLoopFactorial.javaweek3_src/DoWhileLoopFactorial.javapackage edu.drexel.ct290;
import java.util.Scanner;
publicclassDoWhileLoopFactorial{
/**
* A factorial is calculated by multiplying a number by
* every integer less than itself except zero. For example the
* factorial of 4, written 4!, is 4*3*2*1 = 24.
*/
publiclong calculateFactorial(int number){
// declare and initialize a variable to hold the answer
long factorial=number;
// the do while loop will run the block of code between the braces
// as long as the condition in the while statement is true.
// The different between this and the while loop is that
// here, the code will always execute at least once.
do{
// the print statement can help debug errors is in the code
System.out.println("Fact: "+ factorial +", number: "+ number);
// calculate the next factor
factorial = factorial *(number-1);
// decrement the number so that the next iteration of the loop
// will have the correct value to multiply
number--;
}
while( number >1);
// return the answer to the caller.
return factorial;
}
publicstaticvoid main(String[] args){
// Get the user input
Scanner reader =newScanner(System.in);
System.out.print("What number do you want a factorial for: ");
int number = reader.nextInt();
// Create a DoWhileLoopFactorial class
DoWhileLoopFactorial loopFactorial =newDoWhileLoopFactorial();
// call calculateFactorial to compute the answer
long factorial = loopFactorial.calculateFactorial( number );
// Show the user the answer
System.out.println("The answer is: "+ factorial);
}
}
__MACOSX/week3_src/._DoWhileLoopFactorial.java
week3_src/ForLoopFactorial.javaweek3_src/ForLoopFactorial.javapackage edu.drexel.ct290;
import java.util.Scanner;
publicclassForLoopFactorial{
/**
* A factorial is calculated by multiplying a number by
* every integer less than itself except zero. For example the
* factorial of 4, written 4!, is 4*3*2*1 = 24.
*/
publiclong calculateFactorial(int number){
// declare and initialize a variable to hold the answer
long factorial = number;
// The for loop has three parts:
// initialization: int i=number;
// condition: i>1;
// increment/decrement: i--;
// The variable in the initialization is called the control variable
// The initialization happens once when the loop starts.
// The loop will execute as long as the condition is true.
// The decrement will happen automatically after each iteration.
for(int i=number; i>1; i--){
// the print statement can help debug errors is in the code
System.out.println("Fact: "+ factorial +", i: "+ i);
// calculate the next factor
factorial = factorial *(i-1);
}
// return the answer to the caller.
return factorial;
}
publicstaticvoid main(String[] args){
// Get the user input
Scanner reader =newScanner(System.in);
System.out.print("What number do you want a factorial for: ");
int number = reader.nextInt();
// Create a WhileLoopFactoria.
This project calls for the modification of the DollarFormat clas.pdfjibinsh
This project calls for the modification of the \"DollarFormat\" class that is in listing 6.14 (p. 424-
425) of the textbook. Access the file named \"DollarFormat.java\" and modify as instructed in
the problem statement. Access the test application to test your modifications when you produce
\"TruncatedDollarFormat\". Start by going into JGRASP and open \"DollarFormat.java\",
rename the class to \"TruncatedDollarFormat\" and save the file as
\"TruncatedDollarFormat.java\", then make the necessary modifications as defined in the
problem statement, save and compile the file, then open the \"TruncatedBankAccount\"
application. Review the TruncatedBankAccount source code to see how each of the methods are
called. DO NOT make any changes to the TruncatedBankAccount application but instead modify
your TruncatedDollarFormat class to accommodate it.
this is the file that needs to be modified
public class TruncatedDollarFormat
{
/**
Displays amount in dollars and cents notation.
Rounds after two decimal places.
Does not advance to the next line after output.
*/
public static void write(double amount)
{
if (amount >= 0)
{
System.out.print(\'$\');
writePositive(amount);
}
else
{
double positiveAmount = -amount;
System.out.print(\'$\');
System.out.print(\'-\');
writePositive(positiveAmount);
}
}
//Precondition: amount >= 0;
//Displays amount in dollars and cents notation. Rounds
//after two decimal places. Omits the dollar sign.
private static void writePositive(double amount)
{
int allCents = (int)(Math.round(amount * 100));
int dollars = allCents / 100;
int cents = allCents % 100;
System.out.print(dollars);
System.out.print(\'.\');
if (cents < 10)
System.out.print(\'0\');
System.out.print(cents);
}
/**
Displays amount in dollars and cents notation.
Rounds after two decimal points.
Advances to the next line after output.
*/
public static void writeln(double amount)
{
write(amount);
System.out.println( );
}
}
this is the test file
import java.util.*;
public class TruncatedBankAccount
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
double initialBalance;
double interestRate;
double newBalance; // after 10 years
char answer; // sentinel to repeat or end program
int iteration; // loop counter
do // repeat entire program if user says yes
{
System.out.println(\"Please enter an initial balance \"
+ \"(dollars.cents):\");
initialBalance = keyboard.nextDouble();
System.out.println
(\"Please enter an interest rate in percent \"
+ \"(e.g. 5.25):\");
interestRate = keyboard.nextDouble();
System.out.print(\"In ten years an initial balance of \");
TruncatedDollarFormat.writeln(initialBalance);
System.out.println(\" at an interest rate of \"
+ interestRate + \"% will be worth:\");
// compound annually
newBalance = initialBalance;
for(iteration =1; iteration <= 10; ++iteration)
newBalance = newBalance
+ (interestRate/100) * newBalance;
TruncatedDollarFormat.write(newBalance);
System.out.println(\" compounded annually\");
// compound.
import java.util.Scanner;Henry Cutler ID 1234 7202.docxwilcockiris
import java.util.Scanner;
/*
Henry Cutler ID 1234 7/20/2015
Assignment #5, 3 features in 1 program
Solution
for Assignment#5 COP2800
Pseudocode:
Program has three features, all in a single program that are user selectable.
Prompt with options and get user choice inside a while statement ( true )
If 1 is entered:
Using a while and for loop, print out the ASCII table from ! to ~.
If 2 is entered:
Prompt the user for number of times to flip for head or tails using the random method. Count number of each and when the request times are done, print out the results.
If 3 is entered:
Prompt the user for a strings and print back the count of vowels and letters
Any other input entered program will exit using a break statement, otherwise loops back to prompt user for feature selection.
*/
public class Module5 {
public static void main(String[] args) {
// prompt the user
System.out.println("Welcome to Henry\'s 3 in 1 Programming Assignment for Module 5\n");
// create Scanner Object
Scanner input = new Scanner(System.in);
// loop until break
while(true){
// new lines for readability
System.out.print("\n");
// Prompt user for choices
System.out.print("Enter 1 for ASCII Table \nEnter 2 for Heads or Tails\nEnter 3 for Count Vowels & Letters\nAny other input will exit");
int choice = input.nextInt();
// Consume newline left-over
input.nextLine();
// first feature
if(choice == 1){
// start value is !
int value = (int) '!';
// newline for formating
System.out.println("You Selected ASCII Table!\n");
// start at ~ which is 33 decimal
while( value <= '~')
{
// print out 20 in a line
for( int count = 0; count < 20; count ++ ){
if( value <= '~'){
// print single value
System.out.print( (char) value++ );
}
else {
// break when we are at last char to print
break;
}
}
// New line every 10
System.out.print("\n");
}
// New line at exit
System.out.print("\n");
}
else if(choice == 2){
// Prompt user
System.out.println("You Selected Head or Tails!");
System.out.println("\nHow many flips would you like to try?");
// get value
int count = input.nextInt();
// clear
input.nextLine();
int headCount = 0;
int tailCount = 0;
// run for a count provided by user
for (int i = 0; i < count; i++) {
// get random number
if (Math.random() > 0.5){
// increment heads
headCount++;
}
else {
// increment tails
tailCount++;
}
}
System.out.println("Head count: " + headCount + " tail count: " + tailCount);
}
else if(choice == 3){
// Prompt user
Sys.
Using c++Im also using a the ide editor called CodeLiteThe hea.pdffashiongallery1
Typed out please In a short and simple response comment on this persons answer for masonry
work Additives combined with concrete to achieve certain properties are called what? Name a
few that would benefit the Engineer and Customer.
Response - Additives to concrete are utilized to provide certain benefits when placing concrete.
These additives called \"Admixtures\" can be used to speed up the curing process, slow down the
curing process, or help in working with concrete during cold temperatures. Retarders can be
added to concrete to slow down curing. Accelerators can be used to speed up the curing. The
most advanced additive is the Air-entrainment agent which gives mason the ability to work with
concrete in colder months.
Typed out please In a short and simple response comment on this persons answer for masonry
work Additives combined with concrete to achieve certain properties are called what? Name a
few that would benefit the Engineer and Customer.
Response - Additives to concrete are utilized to provide certain benefits when placing concrete.
These additives called \"Admixtures\" can be used to speed up the curing process, slow down the
curing process, or help in working with concrete during cold temperatures. Retarders can be
added to concrete to slow down curing. Accelerators can be used to speed up the curing. The
most advanced additive is the Air-entrainment agent which gives mason the ability to work with
concrete in colder months.
Response - Additives to concrete are utilized to provide certain benefits when placing concrete.
These additives called \"Admixtures\" can be used to speed up the curing process, slow down the
curing process, or help in working with concrete during cold temperatures. Retarders can be
added to concrete to slow down curing. Accelerators can be used to speed up the curing. The
most advanced additive is the Air-entrainment agent which gives mason the ability to work with
concrete in colder months.
Solution
The response of the person is good. He/she explained the admixtures and their applications pretty
well and also explained accelators, retarders and air entertainment in a simple straight forward
fashion.Overall i would say that the answer is satisfactory.
I will like to add \"PLASTICIZERS\" in the list of admixtures that would benefit the engineer
and customer. Plasticizers are water reducing admixtures and are added to the concrete mix for
making it more plastic without any further addition of water. In other words, they reduce the
quantity of water required to make concrete mixture of better plasticity.
PLEASE HIT LIKE BUTTON IF YOU FIND MY ANSWER SATISFACTORY.
THANK YOU..
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...Doug Jones
We rarely dive into current programming languages, touting the next new framework or the new features that will be out next year. This is about JavaScript the language as it exists today, what I picked up in going from C# to JS, and what C# picked up from JS along the way as well. It is based on Douglas Crockford's seminal book "JavaScript: The Good Parts".
Goals1)Be able to work with individual bits in java.2).docxjosephineboon366
Goals
1)
Be able to work with individual bits in java
.
2)
Understand the serializable interface.
3)
Understand the comparable interface.
4)
Answer questions about a general-purpose class to be developed.
5)
Understand the use of a driver program for ‘glass box’ debugging.
6)
Develop a program that can grade true/false tests.
Synthesis Questions
1.
Why is it a good idea to test a general class with a driver program before trying to use it?
2.
What is the difference between black box and glass box debugging?
3.
In pseudo-code, describe
CreateTest.java.
4.
In pseudo code, describe the driver program that is provided below.
5.
If x = 37, y=23, z=-110, r=-32 answer the following questions. Assume that we are working with bytes. To answer these questions, you will need to convert from decimal to binary. Remember that
System.out.println
DOES NOT print binary values. You will need to convert your results to decimal. Of course you can verify your results by computer. Remember that there will be questions like this on the quiz, so try them yourself first.
a.
System.out.println
(
x&y
);
b.
System.out.println
(
x^y
);
c.
System.out.println
(~
x|y
);
d.
System.out.println
(~x>>2);
e.
System.out.println
((byte)(z<<(~r>>4)));
f.
System.out.println
((byte)(x + (x<<1) + (x<<2) + (x<<3)));
g.
System.out.println
(y>>>3);
h.
System.out.println
(
x&y|z^r
);
i.
System.out.println
(~x + x);
j.
System.out.println
(x|(3<<4));
6.
In
about
a sentence, give a reasonable example of when the following operators would be useful when working with strings of bits.
a.
or operation (|):
b.
and operation (&):
c.
exclusive or operation (^):
d.
left shift operation: (<<):
7.
Suppose we need to create a multiple-choice exam, where each question has four possible choices. Briefly describe (in a few sentences) how we could create a new class that uses inheritance that would allow this. Giving class API and a brief description of the needed methods would also suffice.
8.
Suppose we needed to modify the
BitMap
class to handle a bit stream of up to
16384
bits. Briefly describe the changes necessary to handle this refinement. Can you think of a way that the maximum number of bits to be handled is completely flexible?
Description
1)
The first step is to develop a general-purpose class that will be able to perform operations on strings of bits. The class API follows:
public class
BitMap
implements Comparable,
Serializable
{ public static final int BITSIZE = 64;
private
long bitString;
public BitMap
() // Three constructors.
public
BitMap
(String s)
throws
IndexOutOfBoundsException,ArithmeticException
public
BitMap
(
boolean
[] bits)
throws
IndexOutOfBoundsException
private
long
bitMask
(
int
b) // Other class methods.
public void
setBit
(
int
b)
public void
clearBit
(
int
b)
public
boolean
checkBit
(
int
b)
public
int
countTrue
()
public void
clearAll()
public void
setAll()
.
9 11 2
5 14 4
4 6 4
1 15 5
7 9 3
9 16 4
1 2 5
8 8 4
3 12 4
3 11 5
5 19 5
4 19 4
1 11 5
7 15 1
7 8 3
7 6 1
8 19 4
1 8 5
9 9 3
6 2 2
2 11 3
2 10 3
6 16 1
0 1 3
3 3 3
3 10 1
6 6 4
4 3 5
2 3 4
7 1 5
6 8 5
0 13 1
2 5 3
0 12 5
7 18 3
2 0 3
7 3 1
[IFT 102]
Introduction to Java Technologies
Lab 2: Control Flow & Arrays
Score: 50 pts (10 pts * 5)
I. Prelab Exercises (10 pts)
A. Textbook Sections 5.1-5.3
1. Rewrite each condition below in valid Java syntax (give a boolean expression):
a. x > y > z
b. x and y are both less than 0
c. neither x nor y is less than 0
d. x is equal to y but not equal to z
2. Suppose gpa is a variable containing the grade point average of a student. Suppose the goal of a program is to let a student know if he/she made the Dean’s list (the gpa must be 3.5 or above). Write an if... else... statement that prints out the appropriate message (either “Congratulations—you made the Dean’s List” or “Sorry you didn’t make the Dean’sList”).
3. Complete the following program to determine the raise and new salary for an employee by adding if ... else statements to compute the raise. The input to the program includes the current annual salary for the employee and a number indicating the performance rating (1=excellent, 2=good, and 3=poor). An employee with a rating of 1 will receive a 6% raise, an employee with a rating of 2 will receive a 4% raise, and one with a rating of 3 will receive a 1.5% raise.
// ************************************************************
// Salary.java
// Computes the raise and new salary for an employee
// ************************************************************
import java.util.Scanner;
public class Salary
{
public static void main (String[] args)
{
double currentSalary; // current annual salary
double rating; // performance rating
double raise; // dollar amount of the raise
Scanner scan = new Scanner(System.in);
// Get the current salary and performance rating
System.out.print ("Enter the current salary: ");
currentSalary = scan.nextDouble();
System.out.print ("Enter the performance rating: ");
rating = scan.nextDouble();
// Compute the raise -- Use if ... else ...
// Print the results
System.out.println ("Amount of your raise: $" + raise);
System.out.println ("Your new salary: $" + currentSalary + raise);
}
}
B. Textbook Section 5.4
In a while loop, execution of a set of statements (the body of the loop) continues until the boolean expression controlling the loop (the condition) becomes false. As for an if statement, the condition must be enclosed in parentheses. For example, the loop below prints the numbers from 1 to LIMIT:
final int LIMIT = 100; // setup
int count = 1;
while (count <= LIMIT) // condition
{ // body
System.out.println(count); // -- perform task
count = count + 1; // -- update condition
}
There are three parts to a loop:
· The setup, or initialization. This comes before the actual loop, and is where variables are initialized in preparation for the first time through the loop..
1. The link to download
CMIS 212 Module 2 Assignment
Part 1:
1. "Java How to Program" textbook (JHtP) Ex3.5
2. Ex3.11.
4. Ex3.13.
Hints for Ex3.11:
a). After you declare the second String instance variable, you need to modify
your constructor to:
//Constructor:
public GradeBook( String course, String instructor )
{
setCourse(course);
setInstructor(instructor);
} // end constructor
b). Note that there is NO main( ) method in GradeBook.java. The
GradeBookTest.jva on Pages 89 - 90 DOES have main( ) method. On line 11
(and 13 as well) of GradeBookTest.java program on Page 90, you create an
object of GradeBook. Every time, you run a Java program, it looks for the
main( ) method first, in other words, you must have a main() method in the
program you want to run. As you create an object of the GradeBook program
you modified in Ex3.11 a-d, you use the newly changed GradeBook. If you try
to run a program without a main() method, you will get "main method not
found" error.
c). Now, since you have TWO arguments in the GradeBook constructor, when
you create a new object of GradeBook in the GradeBookTest program, you
need to pass TWO values over, for example:
GradeBookGradeBook("BIBL 105", "Sam Smith" );
If you just pass one or 3 values over, you will get an error. Alos, make sure
the values you pass over match with the data type you have in the GradeBook
constructor.
d). For Ex3.11, after you make changes instructed in a-d on p.104, to compile
the programs:
javac GradeBook.java GradeBookTest.java
To run the program:
java GradeBookTest
2. Hints for Ex3.13: // Note: this one does NOT have main() method
// Later, you will create InvoiceTest.java to instantiate Invoice objects
// Invoice class: Invoice.java
public class Invoice
{
private String partNumber;
private String partDescription;
private int quantity;
private double pricePerItem;
// four-argument constructor
public Invoice( String part, String description, int count, double price )
{
;
;
if ( count > 0 ) // determine whether count is positive
; // valid count assigned to quantity
if ( price > 0.0 ) // I will let you finish the rest:
...
} // end four-argument Invoice constructor
// set part number:
public void setPartNumber( String part )
{
; //accept the passed part value and assign it to instance variable partNumber
} // end method setPartNumber
//You will finish the other set and get methods:
...
Hints for InvoiceTest.java:
//Q1: Ask yourself, what's the purpose of a Test program?
//Q2: Why do we have Invoice.java and InvoiceTest.java? Why not combining
them in one? Think from object-oriented programming point of view.
public class InvoiceTest
{
public static void main( String args[] )
{ //create an instance of Invoice passing 4 argument values here.
//Question1: Do you have 4 arguments in the Invoice constructor?
//Question2: What would happen if you just pass 3 values here?
Invoice Invoice( "1234", "Hammer", 2, 14.95 );
// display invoice1
System.out.println( "Original invoice information" );
System.out.printf( "Part number: %sn", invoice1.getPartNumber() );
3. //I will let you finish the rest of the program to display more information of
invoice1:
Part 2:
"Java How to Program" textbook (JHtP) Ch4:
1. Ex4.13 In addition to answer the question of "What type of repetition would
be appropriate for calculating the sum of the first 100 positive integers?", also
write down your loop statement to calculate the sum of the first 100 positive
integers, that is to get total which is sum of 1 + 2 + 3 + ... + 100.
2. Ex4.15
3. Ex4.17
Hints for Ex4.17:
1. You will have two files:
a) Gas.java and
b) GasTest.java. The Gas.Test.java is very simple:
public class GasTest
{
public static void main( String args[] )
{
Gas Gas();
application.calculateMPG();
} // end method main
} // end class GasTest
2. In Gas.java file, obviously you will need a method called calculateMPG,
which will ask the user to input miles driven and gallons used as many times
as the user wants until the user does not want to enter anymore (for example,
you can tell the user to enter -1 if they want to stop entering).
public void calculateMPG()
{
Scanner Scanner( System.in );
int miles; // miles for one tankful
int gallons; // gallons for one tankful
int ; // total mailes for trip
int ; // total gallons for trip
double milesPerGallon; // miles per gallon for tankful
double totalMilesPerGallon; // miles per gallon for trip
...
4. // exit if the input is -1; otherwise, proceed with the program
while ( miles != -1 )
{
// prompt user for gallons and obtain the input from user
System.out.print( "Enter gallons: " );
();
...
// add gallons and miles for this tank to totals:
...
// calculate miles per gallon for the current tank
if ( gallons != 0 )
{ milesPerGallon = (double) miles / gallons;
System.out.printf( "MPG this tankful: ....
} // end if statement
// calculate miles per gallon for the total trip
if ( totalGallons != 0 )
{
...
} // end if statement
// prompt user for new value for miles:
System.out.print( "Enter miles (-1 to quit): " );
//retrieve the value and save it into miles:
...
} // end while loop
} // end method calculateMPG
//Note that this is NOT a complete program, just a hint.
Part 3:
T.4
4.x 13
Part 4:Top of Form
5. 1. SJP Tutorial 8.
2. SJP Ex8.12 (Mortgage Calculator Application)
Hint for Ex8.12:
To increment the year by 5 in the while loop:
while ( years <= 30 )
{
// calculate payment period:
...
// getmonthlyPayment:
...
// appendresultintooutputJTextArea:
...
years += 5; // incrementcounter
}