|
Variables or expressions as parameters |
|
Just as values can be parameters to methods,
it’s also possible to use variable names, and even expressions, as
parameters. An example of where this
would be needed is a program that prompts the user to enter the coordinate of
the cell that he or she wishes to color red.
Here’s the full program: import java.util.Scanner; import java.awt.Color; public class ColorACell { public
static void main(String[] args) { //
create Board object Board b
= new Board(10, 10); //
create Scanner object Scanner
input = new Scanner(System.in); //
obtain input from user and store in variables System.out.print("Enter the x-coordinate of the cell
you'd like
to color (max is 9): "); int xCoord = input.nextInt(); System.out.print("Enter its y-coordinate (max is 9):
"); int yCoord = input.nextInt(); // use
the variables as parameters b.fillCell(xCoord, yCoord, Color.red); } } If you’re running this program in DrJava, you will find the prompt to enter the coordinate
values in the Interactions pane. |