Monday, January 27, 2014

Input and Output in Java

In this blog post, you will learn how to read user input and how to control the appearance of the output that your programs produce.

Reading Input

You can make programs more flexible if you ask the user for inputs rather than using fixed values.

When a program asks for user input, it should first print a message that tells the user which input is expected. Such a message is called a prompt.

System.out.print("Please enter the number of bottles: "); // Display prompt
Use the print method, not println, to display the prompt. You want the input to appear after the colon, not on the following line. Also remember to leave a space after the colon.
A supermarket scanner reads bar codes. The Java Scanner reads numbers and text.


To read keyboard input, you use a class called Scanner. You obtain a Scanner object by using the following statement:

Scanner in = new Scanner(System.in);

  • When using the Scanner class, you need to carry out another step: import the class from its package.
  • The Scanner class belongs to the package java.util.

To use the Scanner class from the java.util package, place the following declaration at the top of your program file:

import java.util.Scanner;

Note: Only the classes in the java.lang package are automatically available in your programs. Java classes are grouped into packages. Use the import statement to use classes from packages.

int bottles = in.nextInt();
double price = in.nextDouble();

String nextWord = in.next(); // reads next token, default delimiter is white space.
String line = in.nextLine(); // returns entire line, excluding line separator.

Methods for Scanner objects:

nextByte() -
nextShort() - 
nextInt() - reads a number of int type
nextLong() - 
nextFloat() -
nextDouble() - 
next() - reads a string ends before whitespace char
nextLine() -  reads a line of text, ending with enter key pressed (new line separator)

Formatted Output


Use the printf 
method to specify 
how values should 
be formatted.

Ex: System.out.printf("%10.2f", price); // specified field width of 10 characters

.2f indicates, 2 digits after dot (.)
10 indicates, the total width is 10 digits, that is including dot and 2 digits.

The construct %10.2f is called a format specifier: it describes how a value should be formatted.

%s - for strings
%d - for integers


No comments:

Post a Comment