Java Reference
In-Depth Information
To fix the error, break the string into separate substrings, and use the concatenation
operator ( + ) to combine them:
System.out.println( "Introduction to Java Programming, " +
"by Y. Daniel Liang" );
break a long string
Tip
This example consists of three steps. It is a good approach to develop and test these
steps incrementally by adding them one at a time.
incremental development and
testing
2.1
Identify and fix the errors in the following code:
Check
Point
1 public class Test {
2
public void main(string[] args) {
3
int i;
4
int k = 100.0 ;
5
int j = i + 1 ;
6
7 System.out.println( "j is " + j + " and
8
k is " + k);
9 }
10 }
2.3 Reading Input from the Console
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 stan-
dard 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 syn-
tax 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 methods listed in Table 2.1
to read various types of input.
For now, we will see how to read a number that includes a decimal point by invoking the
nextDouble() method. Other methods will be covered when they are used. 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
import class
2
3 public class ComputeAreaWithConsoleInput {
4
public static void main(String[] args) {
5
// Create a Scanner object
6
7
Scanner input = new Scanner(System.in);
create a Scanner
 
 
Search WWH ::




Custom Search