Java Reference
In-Depth Information
2.1
✓
✓
Identify and fix the errors in the following code:
Check
Point
1
public class
Test {
2
public void
main(string[] args) {
3
double
i =
50.0
;
4
double
k = i +
50.0
;
5
double
j = k +
1
;
6
7 System.out.println(
"j is "
+ j +
" and
8
k is "
+ k);
9 }
10 }
Reading input from the console enables the program to accept input from the user.
Key
Point
In Listing 2.1, the radius is fixed in the source code. To use a different radius, you have to
modify the source code and recompile it. Obviously, this is not convenient, so instead you can
use the
Scanner
class for console input.
Java uses
System.out
to refer to the standard output device and
System.in
to the
standard input device. By default, the output device is the display monitor and the input
device is the keyboard. To perform console output, you simply use the
println
method to
display a primitive value or a string to the console. Console input is not directly supported
in Java, but you can use the
Scanner
class to create an object to read input from
System.in
,
as follows:
VideoNote
Obtain input
Scanner input
=
new
Scanner(System.in);
The syntax
new Scanner(System.in)
creates an object of the
Scanner
type. The syntax
Scanner input
declares that
input
is a variable whose type is
Scanner
. The whole line
Scanner input = new Scanner(System.in)
creates a
Scanner
object and assigns its
reference to the variable
input
. An object may invoke its methods. To invoke a method on
an object is to ask the object to perform a task. You can invoke the
nextDouble()
method to
read a
double
value as follows:
double
radius = input.nextDouble();
This statement reads a number from the keyboard and assigns the number to
radius
.
Listing 2.2 rewrites Listing 2.1 to prompt the user to enter a radius.
L
ISTING
2.2
ComputeAreaWithConsoleInput.java
1
import
java.util.Scanner;
// Scanner is in the java.util package
2
3
public class
ComputeAreaWithConsoleInput {
4
import class
public static void
main(String[] args) {
5
// Create a Scanner object
6
Scanner input =
new
Scanner(System.in);
create a
Scanner
7
8
// Prompt the user to enter a radius
9 System.out.print(
"Enter a number for radius: "
);
10
double
radius = input.nextDouble();
read a
double
11
12
// Compute area
13
double
area = radius * radius * 3.14159;
14
15
// Display results
Search WWH ::
Custom Search