Making decisions

$\triangleright$
If we change the test program to create a different quadratic equation:

QuadraticEquation qe1 = new QuadraticEquation(2.0, 10.0, -12.0);

we get the following output:

2.0*x^2 + 10.0*x + -12.0

Not quite, what we wanted!

$\triangleright$
First we want to input different equations without recompilation. This leads to a new version of TestQuadraticEquation: TestQuadraticEquation.java

$\bullet$
An array is a data structure that combines several elements of the same base type. An array of NUMBER elements is created with

     BASETYPE[] myArray;
     myArray = new BASETYPE[NUMBER];
 

     myArray[0], myArray[1] ... myArray[NUMBER-1]
 

$\diamond$
We create an array of 3 integers and set its values:

     integer[] vec = new integer[3];
     vec[0] = 42;
     vec[1] = 28;
     vec[2] = vec[0] + vec[1];   //  = 70
 

$\bullet$
A Java program can be called with additional parameters, separated by spaces, like

java MYCLASS PAR1 PAR2 .. PARN

The parameters are collected in an array of Strings and passed as argument to the main method.

$\diamond$
If we start our example with

java TestQuadraticEquation 2.0 -10.0 3

the argument array arg has the values

     arg[0] = "2.0"
     arg[1] = "-10.0"
     arg[2] = "3"
 

$\triangleright$
The static method parseDouble of class Double does its best to translate a String into a double value.

$\triangleright$
If TestQuadraticEquation is called with less than 3 parameters or if one of the parameters can't be transformed to a number, we get an error message.

$\triangleright$
Now we extend QuadraticEquation to be able to print negative coefficients: QuadraticEquation.java

$\triangleright$
The translation of a double value to a String works different for positive and negative numbers: negative doubles start with a minus sign, positive don't start with a plus sign.

The method toSignedString returns a double with plus or minus sign and extra space. It works by using always a positive value for the translation and adding the sign explicitly.

To do this, we need a way to decide between the values of the double.

$\bullet$
Decisions can be programmed with the alternative, written as

     if (CONDITION) {
       DO SOMETHING
     } else {
       DO SOMETHING ELSE
     }
 

$\diamond$
Special boolean expressions are made up from comparisons:

expression meaning
(d $>$ 0) greater than
(d $<$= 0) less than or equal
(d == 0) equal
(d != 0) not equal

$\triangleright$
The method toSignedString is private, which means that it can be used only for internal purposes of the class (for the print method in our example).

previous    contents     next

Peter Junglas 8.3.2000