L5: Input and Output in Java
Introduction to Input and Output
- Java allows interaction with the user via input and output operations.
- The
Scanner
class provides a simple way to read inputs from the terminal.
Using the Scanner Class
To use the
Scanner
class, it must be imported from thejava.util
package:import java.util.Scanner;
Instantiating a Scanner Object: Create a
Scanner
object to read input from the terminal:Scanner input = new Scanner(System.in);
System.in
connects the program to the standard input stream (keyboard input).
Reading Input:
nextLine()
: Reads an entire line of input, including spaces until the newline character is encountered. Useful for capturing strings with multiple words.String line = input.nextLine();
next()
: Reads the next token (a word or chunk of data separated by whitespace) and stops before spaces.String word = input.next();
Error Handling with
Scanner
:hasNext()
: Checks if the input stream has more tokens to read. Returnstrue
if there’s more input.if (input.hasNextInt()) { int number = input.nextInt(); }
If an invalid input type is encountered (e.g., trying to read an integer from a non-numeric input), a runtime error occurs. Use
hasNext()
methods (likehasNextInt()
) to prevent this.
Common Issues:
Mixing
nextLine()
with othernext()
methods can cause problems sincenextLine()
reads the newline character as part of the input. UsenextLine()
immediately after othernext()
calls to clear the input buffer:int age = input.nextInt(); input.nextLine(); // Clear the buffer String name = input.nextLine();
Java Packages
- Packages: Collections of related classes grouped together for specific functionalities.
java.lang
Package: Automatically imported; contains fundamental classes likeString
,System
,Math
.java.util
Package: Must be imported manually; contains utility classes such asScanner
,ArrayList
.Importing a package:
import java.util.Scanner;
Use
import java.util.*;
to import all classes within a package (not recommended unless necessary to avoid ambiguity).
Formatting Output
- Java offers various ways to format output, including
System.out.printf()
,String.format()
, and formatting classes fromjava.text
.
System.out.printf()
Used for formatted output with placeholders called format specifiers:
System.out.printf("Hello, %s! You are %d years old.\n", "John", 25);
- Format Specifiers:
%s
- String%d
- Integer%f
- Floating-point (default to 6 decimal places)
Format Specifier Conversion Applied %%
Inserts a % sign %x %X
Integer hexadecimal %t %T
Time and Date %s %S
String %n
Inserts a newline character %o
Octal integer %f
Decimal floating-point %e %E
Scientific notation %g
Causes Formatter to use either %f or %e, whichever is shorter %h %H
Hash code of the argument %d
Decimal integer %c
Character %b %B
Boolean %a %A
Floating-point hexadecimal - General format:
% [flags] [width] [.precision] [argsize] typechar
- Modifiers: Control the output’s precision, width, alignment, etc.:
%.2f
- Limits floating-point to 2 decimal places.%10s
- Reserves 10 spaces for a string, right-aligned by default. Use%-10s
for left alignment.
- Format Specifiers:
String.format()
Similar to
printf
, but returns a formatted string instead of printing it:String formatted = String.format("Total: %.2f", 123.456);
Number Formatting
NumberFormat
Class:Used for currency and percentage formatting.
Must be imported from
java.text
:import java.text.NumberFormat;
Example:
NumberFormat currencyFormat = NumberFormat.getCurrencyInstance(); System.out.println(currencyFormat.format(12345.678)); // Outputs: $12,345.68
Supports different locales (e.g.,
Locale.FRANCE
) to format numbers in different currency styles.
DecimalFormat
Class:Customizes numerical formatting based on a specified pattern.
Must be imported from
java.text
:import java.text.DecimalFormat;
Example:
DecimalFormat formatter = new DecimalFormat("0.00"); String formattedNumber = formatter.format(123.456); // Outputs: "123.46"
Patterns:
0
- Guarantees a digit in that position.#
- Optional digit.%
- Displays a percentage by multiplying the number by 100.
Short Coding Problems Involving Command Line Inputs
Read a User’s Name and Age:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter your name: "); String name = input.nextLine(); System.out.print("Enter your age: "); int age = input.nextInt(); System.out.printf("Hello, %s! You are %d years old.\n", name, age); } }
Format a Price with Currency:
import java.text.NumberFormat; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter the price: "); double price = input.nextDouble(); NumberFormat currencyFormat = NumberFormat.getCurrencyInstance(); System.out.println("Formatted price: " + currencyFormat.format(price)); } }