4 OK 45 OK 456 OK 923X BAD 23 876 OK: the first group ends after the "3"
The last line is OK.
Scanner
reads characters just far enough to make one int
and stops in the
middle of the line.
If the program had two calls to nextInt()
the second call would scan the 876.
EchoSquare.java
Here is the program shown the the previous picture. It computes the square of an integer entered (as characters) by the user.
import java.util.Scanner; public class EchoSquare { public static void main (String[] args) { Scanner scan = new Scanner( System.in ); int num, square; // declare two int variables System.out.println("Enter an integer:"); num = scan.nextInt(); square = num * num ; // compute the square System.out.println("The square of " + num + " is " + square); } }
Here is a picture of it running:
Please run this program and play with it. Beginning programmers are often confused about "character data" and "numeric data" and conversions between the two. Take the opportunity to make sure you know what is going on to avoid future confusion.
Try some correct input and incorrect. Try several integers on one line. Perhaps modify the program so that it asks for two integers and computes the square of each.
Do you think that the following input would work with this program?
twelve hundred