|
The method call System.out.println(area) in the Java program:
public class ComputeArea
{
public static void main(String[] args)
{
double radius;
double area;
// (1) Assign a radius
radius = 20;
// (2) Compute area
area = 3.14159 * radius * radius;
// (3) Print result
System.out.println(area);
}
}
|
means: execute the method call println(area) with the object System.out (= console)
|
Here is the original ComputeArea program:
public class ComputeArea
{
public static void main(String[] args)
{
double radius;
double area;
// (1) Assign a radius
radius = 20;
// (2) Compute area
area = 3.14159 * radius * radius;
// (3) Print result
System.out.println(area);
}
}
|
DEMO: demo/02-elem-prog/02-scanner/ComputeArea.java
We change it so the program will read in the radius from a Scanner object named input:
public class ComputeArea
{
public static void main(String[] args)
{
double radius;
double area;
Scanner input = new Scanner(System.in); // (A)
// (1) Read in radius from System.in
radius = input.nextDouble(); // (B) (**) Compile -> error
// (2) Compute area
area = 3.14159 * radius * radius;
// (3) Print result
System.out.println(area);
}
}
|
BlueJ says: Unknown type: Scanner
Fix (reason): we must import the Scanner class from the Java library before we can use it in the program:
import java.util.Scanner; // (**) Fix error (BlueJ gave a HINT !) public class ComputeArea { public static void main(String[] args) { double radius; double area; Scanner input = new Scanner(System.in); // (A) // (1) Read in radius from System.in radius = input.nextDouble(); // (B) (**) No error // (2) Compute area area = 3.14159 * radius * radius; // (3) Print result System.out.println(area); } } |
Demo (It's better to print a prompt message !!)
Write a program that reads in 3 numbers and prints out the average of the numbers
|
|
Write a program that reads in 3 numbers and prints out the average of the numbers
import java.util.Scanner; // Scanner is in the java.util package
public class ComputeAverage
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
// Prompt the user to enter three numbers
System.out.print("Enter three numbers: ");
double number1 = input.nextDouble();
double number2 = input.nextDouble();
double number3 = input.nextDouble();
// Compute average
double average = (number1 + number2 + number3) / 3;
System.out.println(average);
}
}
|
DEMO: demo/02-elem-prog/03-CompAvg/ComputeAverage.java