0% found this document useful (0 votes)
78 views

ICTD 351: Introduction To Computer Programming For The Mathematics Teacher

This document provides instructions for running a Java application from the command line and passing arguments to it. It explains that arguments are extra information sent to a program when it is run. The first argument is provided after the application name, and additional arguments are separated by spaces. An example program called UserArgument is provided to demonstrate how to accept and print arguments. The document guides the reader through customizing the project in NetBeans to specify arguments when running the example program.

Uploaded by

Prince Boahene
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
78 views

ICTD 351: Introduction To Computer Programming For The Mathematics Teacher

This document provides instructions for running a Java application from the command line and passing arguments to it. It explains that arguments are extra information sent to a program when it is run. The first argument is provided after the application name, and additional arguments are separated by spaces. An example program called UserArgument is provided to demonstrate how to accept and print arguments. The document guides the reader through customizing the project in NetBeans to specify arguments when running the example program.

Uploaded by

Prince Boahene
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 37

ICTD 351:

Introduction to Computer
Programming for the
Mathematics Teacher

THE MATH CLASS


THE MATH CLASS
If we use only arithmetic operators to express
numerical computations it is very limiting.
Many computations require the use of mathematical
functions.
The Math class in the java.lang package contains
commonly used mathematical functions.
It also contains two class constants: PI and E.
This is the description of some of the Math class
methods. (see p.59 of Programming Codes).
NB:
1.Because the Math class is part of the java
language, we don’t import it in order to use its
methods.
2.To use any of these methods we use the dot
operator. For example to find the square root of
x in a program, we will write Math.sqrt(x).
Let us see programs that use methods from the Math
class to solve problems.
1.Write an application to solve quadratic equations of
the form ax 2
 bx  c  0
where a, b, and c are real numbers and a ≠ 0. Use the
formula: b  b  4ac
2
x
2a
Solution
Note that the formula consists of two parts (the two
roots): b  b 2  4ac b  b 2  4ac
x1  and x2 
2a 2a
The program Quadratic.java (p. 10) illustrates this.
Use your program to find the roots of the following
quadratic equations:
1.2x2 – 3x – 2 = 0
2.(2x – 1)2 = 9
3.4x2 – 20x + 17 = 0
4.x2 + x + 1 = 0
2. Write an application that inputs from the user the
radius of a circle and calculates and prints out the
circumference and the area correct to 3 decimal
places. Use the predefined constant Math.PI for the
value of π. Save your file as Circle.java (p. 11)
TYPE CONVERSION
If two types are compatible, Java performs the
conversion automatically.
Eg. It is always possible to assign an int value to a long
variable.
However, not all types are compatible.
Eg. There is no conversion defined from double to
byte.
It is possible to obtain a conversion between
incompatible types.
To do so, we must use a cast, which performs an
explicit conversion between incompatible types.
Java’s Automatic Conversions
When one type of data is assigned to another type, an
automatic type conversion will take place if the
following two conditions are met:
 The two types are compatible.
 The destination type is larger than the source type.
Eg. The int type is always large enough to hold all
valid byte values so no explicit cast statement is
required.
Automatic Type Promotion in
Expressions
In addition to assignments, there is another place
where certain type conversions may occur.
In an expression, the precision required of an
intermediate value will sometimes exceed the
range of either operand.
Let us examine the following expression:
byte a = 40;
byte b = 50;
byte c = 100;
byte d = a * b / c;
The result of the intermediate term a*b easily
exceeds the range of either its operands.
Java automatically promotes each byte or short
operand to int when evaluating an expression.
This means the expression a*b is performed using
integers - not bytes.
Thus, 2000, the result of the intermediate expression,
50*40, is legal even though a and b are both
specified as type byte.
Automatic conversion can cause confusing compile-
time error.
For example, this seemingly correct code causes a
problem:
byte a = 50;
byte b = a*2;
NetBeans flag this: Incompatible types: possible lossy
conversion from int to byte
This code is attempting to store 50*2, a perfectly valid
byte value back into a byte variable.
However, because the operands were
automatically promoted to int when the
expression was evaluated, the result has also
been promoted to int.
Thus the result of the expression is now of type
int, which cannot be assigned to a byte
variable without the use of a cast because the
destination type is smaller than the source
type.
Type Promotion Rules
In addition to the elevation of bytes and shorts to int,
Java defines several type promotion rules that apply
to expressions.
First, all byte and short values are promoted to int.
Then if one operand is long, the whole expression is
promoted to long.
If one operand is a float operand, the entire
expression is promoted to a float.
If any of the operands is double, the result is double.
Let us take a look at the declarations and the
expression in the next slide.
byte b = 42;
char c = ‘a’;
short s = 1024;
int i = 5000;
float f = 5.67f;
double d = .1234;
double result = (f*b) + (i/c) – (d*s);
In the first subexpression, f*b, b is promoted to a
float and the result is a float.
In the subexpression, i/c, c is promoted to int and the
result is of type int
In d*s, s is promoted to double and the result is
double.
Finally, these three intermediate values float, int, and
double are considered.
The outcome of float plus an int is a float.
The resultant float minus the last double is a double,
which is the type for the final result of the expression.
Casting
The statement int x2 = (int)(x1) will convert a double
value x1 to an integer value x2.
The statement double x4 = (double)(x3) will convert
an integer value x3 to a double value x4.
Let us use the Fibonacci sequence as an example.
The sequence is 1, 1, 2, 3, 5, 8, 13, …
The nth Fibonacci number can be calculated using the
formula:
1  1 5   1 5  
 n n

Fn       
5  2   2  
 
As you see, the terms of the sequence are integers
but the square root and powers are double.
Therefore there is the need to do casting.
Let us break the formula into small pieces to ease in
the writing of the program (divide and conquer).
n n
 1 5   1 5  ab
Let a    , b    , c 
 2   2  5

Let us call this program Fibonacci.java (p. 12)


Write a program that simulates rolling a pair of dice and finds
the sum of the numbers that show up on the dice.
You can simulate rolling one die by choosing one of the
integers 1, 2, 3, 4, 5, or 6 at random. The number you pick
represents the number on the die’s face after it is rolled.
The expression (int)(6*Math.random()) + 1 does the
computation you need to select a random integer from 1 to
6.
[Recall that we used a similar formula in ICTD 241 to simulate
the tossing of a fair die, =int(6*rand())+1, this is because
the return type of random() is a double greater than or
equal to 0 but less than 1 therefore we need to do casting].
Your program should report the number showing on each die
as well as the total roll.
Save your work as RollDice.java (p. 12)
The Scanner class
Another way of inputting data from the keyboard is to
use the Scanner class.
See Addition2.java p.13
Sending Arguments to Applications
You can run Java applications from a
command line using java, a program that
invokes the JVM.
NetBeans uses this behind the scenes
when you run programs.
When a Java program is run as a
command, the JVM loads the application.
Extra information sent to a program is
called an argument.
The first argument, if there is one, is
provided one space after the name of the
application.
Each additional argument also is separated
by a space.
You can send as many arguments as
you want to a Java application (within
reason).
To do something with them, you must
write statements in the application to
handle them.
To see how arguments work in an
application, create a new class in your
project
1. Choose File, New File.
2. In the New File Wizard, choose the
category Java and file type Empty
Java File.
3. Give the class the name UserArgument
and click Finish.
4. Type the program UserArgument (See
page 13 of the Program Code) in the
source code editor and save it.
A Look at the Program
Line 6:
System.out.print(args[0]);
In java, and other programming languages,
arrays are indexed from 0.
That is the first argument is 0
The second argument is 1 (line 7)
Thus this program accepts two arguments
If you click on Run then Run File, you get
an error message:
Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 0
at UserArgument.main(UserArgument.java:6)
This error occurs because the program
expects to receive two arguments when it is
run.
You can specify arguments by customizing the
project in NetBeans:
1. Click Run, Set Project Configuration, Customize.
2. The Project Properties dialog opens.
3. Enter UserArgument in the Main Class text field.
4. In the Arguments field, enter Mike (your first
name) and click OK.
5. Click Run, then Run Main Project
The result is shown in the next slide in bold.
This is the result:
Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 1
at
UserArgument.main(UserArgument.java:7)
Hi, MikeJava Result: 1

You are getting this result because you specified


that you are going to specify two arguments but
you supplied only one
Now let us specify two arguments
1. Click Run, Set Project Configuration, Customize.
2. The Project Properties dialog opens.
3. Enter UserArgument in the Main Class text field.
4. In the Arguments field, enter Mike Amppiah (your
first and last names) and click OK.
5. Click Run, then Run Main Project
The result is shown below in bold.
Hi, Mike Amppiah. How are you?
Now if you have three names, as I have, at step 4,
write your three names, say,
Michael Edmund Amppiah
Now click Run, then Run Main Project
What result do you get?
Only the first and second names appear.
If you want the third name to appear, then you have
to add a third argument.
The program, AddDouble.java (p.13) add
two numbers by sending two arguments
to java application.
Type the program as usual and save.
Click
Run
Set Project Configuration
Customize
In the Main Class field, type AddDouble
Assuming we are adding 2 and 7,
In the Arguments field type 2, leave a
space, then type 7
Click OK
Click
Run
Run Main Project
Problem Set
1. The area of a triangle with sides of length a, b, and
c is given by s ( s  a)( s  b)( s  c)
where s  (a  b  c) / 2
Write a program that inputs the three values of the
sides of a triangle and uses this formula to
calculate the area.
Save the file as areaTriangle.java
Use your program to find the areas of the following
triangles
i. a = 8, b = 11, c = 13; ii. a = 12.3, b = 14.1, c = 13.6
2. A quantity known as the Body Mass Index (BMI) is
used to calculate the risk of weight-related health
problems. BMI is computed by the formula
w
BMI  2
h

where w is weight in kilograms and h is height in


meters.
Write a program that accepts weight and height and
outputs the BMI. Save the file as BMI.java
3. Write a program that reads in two sides a and b of
a triangle, as well as the angle C (in degrees)
between the two sides, then calculates the third
side, c, from the law of cosines:
c  a  b  2ab cos C
2 2 2

Save the file as triangle.java


Use your program to find the third side in the
following triangles
i. a = 11, b = 5, C = 20°
ii. a = 12, b = 7, C = 55°
iii. a = 12, b = 21, C = 95°
4. The distance, d, between two points A(a,b) and
B(c,d) is given by the formula (a  c)2  (b  d )2 .
Write a program that reads in the coordinates of two
points and calculates the distance between them.
Save the file as Distance.java
Use your program to find the distance between the
following pairs of points
i. A(-1,2), B(4,-2)
ii. A(1,1), B(3,4)
5. Write a program that reads in seconds and
displays the number of hours, minutes and
seconds in the given seconds. Save your file as
secondsConverting.java

You might also like