Continuing through the textbook, we'll look at Chapter 5 (pages 27 to 31), and Section 6.1 (pages 33 to 35).
double scale; scale = 2.4;There's also an integer type, int:
int i; i = 5; i = 5.0; // Illegal! scale = 2; // Okay
void show()
Displays this window on the screen.
Two more instance methods from the RobotWindow class illustrate return values:
double requestDouble()
Shows the user a dialog box prompting for a number, and
returns this number.
int requestInt()
Shows the user a dialog box prompting for an integer, and
returns this integer.
We can use an assignment statement to save the value that a method returns:
scale = win.requestDouble(); // Save the user's inputNow look at show again. The word void indicates that that method never returns a value.
| + | addition | |
| - | subtraction | |
| * | multiplication | |
| / | division | |
| % | modulus (remainder) |
Some of these may look familiar; they work the way you'd expect:
scale = 100 - length / 2.0; scale = (100 - length) / 2.0;The modulus operator only works on integers, and returns the remainder:
Combining different numeric types:
if any of the numbers is a double, the result will be a
double.
But beware:
double scale; scale = 1 / 2; // Sets scale to 0.0!
import pgss.*;
public class DrawSquare {
public static void main(String[] args) {
RobotWindow win;
win = new RobotWindow();
win.show();
double length;
length = win.requestInt();
double start;
start = 100 - length / 2;
Robot rob;
rob = new Robot(win, start, start);
rob.move(length);
rob.turn(-90);
rob.move(length);
rob.turn(-90);
rob.move(length);
rob.turn(-90);
rob.move(length);
rob.SwitchOff();
}
}
Parameters can be a variable, a number, or any expression:
rob = new Robot(win, 100 - length / 2, 100 - length / 2);
while ( <condition> ) {
<body>
}
The ability to write loops is very important to allow flexible, general-purpose programs to be written. To demonstrate, we'll rewrite our DrawSquare program using a while loop:
import pgss.*;
public class DrawSquare {
public static void main(String[] args) {
RobotWindow win;
win = new RobotWindow();
win.show();
double length;
length = win.requestInt();
double start;
start = 100 - length / 2;
Robot rob;
rob = new Robot(win, start, start);
int drawn;
drawn = 0;
while(drawn < 4) {
rob.move(length);
drawn = drawn + 1;
rob.turn(-90);
}
rob.SwitchOff();
}
}
This completes all the material that you need for the Assignment 0 program! Whew...