0% found this document useful (0 votes)
36 views28 pages

Java Scanner Class Basics

The document provides an overview of basic input/output in Java using the Scanner class, which allows for reading user input. It discusses the initialization of the Scanner, common methods, and the use of print and printf for output formatting, including escape characters and formatting flags. Additionally, it highlights potential pitfalls with the nextLine() method and demonstrates how to handle them effectively.

Uploaded by

abod900plus
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views28 pages

Java Scanner Class Basics

The document provides an overview of basic input/output in Java using the Scanner class, which allows for reading user input. It discusses the initialization of the Scanner, common methods, and the use of print and printf for output formatting, including escape characters and formatting flags. Additionally, it highlights potential pitfalls with the nextLine() method and demonstrates how to handle them effectively.

Uploaded by

abod900plus
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

CS1701T: Computer Programming in Java

1st Semester 2025

Lecture 3
Basic Input/Output

Source: Dr. [Link] Gaddah


Modified by Dr. Malak AlJabri and Dr. Areej Althobiti 1
Scanner Class

• Scanner is a class that provides methods for inputting words,


numbers, and other data.

• Scanner is provided by [Link], which is a package that contains


various “utility classes”.

• Before we could use Scanner , we have to import it (just


before public class ClassName) like this:
import [Link];

This statement tells the compiler which Scanner class we are referring
to because there might be another class named Scanner

2
Scanner Class
• To initialize the Scanner class, we have to declare/define a Scanner
variable/object named keyboard and creates a Scanner that reads
input from [Link]:

• Syntax:
Scanner keyboard= new Scanner ([Link]);

Note:
• The new operator return a reference(memory location/address) to
the variable keyboard in the memory
• you may name the Scanner variable any name you wish such as: in,
src, source, etc

3
Some Scanner Class Methods

4
Some Scanner Class Methods

5
Keyboard Input Demonstration

6
Keyboard Input Demonstration

Sample
screen
output

7
nextLine()Method Caution
• The nextLine() method reads
• The remainder of the current line,
• Even if it is empty.

• Example
int n;
String s1, s2;
Scanner keyboard = new Scanner ([Link]);

n = [Link]();
s1 = [Link]();
s2 = [Link]();

[Link] ("n: " + n);


[Link] ("s1: " + s1);
[Link] ("s2: " + s2);

8
nextLine()Method Caution
• Why when we read a String followed by an int, everything works just fine.
But when we read an int followed by a String, something strange happens?

• Scanner doesn’t see input as multiple lines as we do; but as a stream of


characters!
42 \n a n d d o n ' t y o u \n

• nextInt returns the value 42. The program then waits for the user to enter
s1 and runs nextLine, which reads characters until it gets to a newline.

• But since the next character is already a newline, nextLine returns the
empty string "".

9
nextLine()Method Caution
• How can we solve this problem?
• We need an extra nextLine after nextInt :
int n;
String s1, s2;
Scanner keyboard = new Scanner ([Link]);

n = [Link]();
[Link](); //// read the newline
s1 = [Link]();
s2 = [Link]();

[Link] ("n: " + n);


[Link] ("s1: " + s1);
[Link] ("s2: " + s2);

10
Keyboard Input Demonstration

11
Keyboard Input Demonstration

Sample
Screen
Output

12
Screen Output
• We've seen several examples of screen output already.
• Example:
[Link]("Enter a whole number from 1
to 99.");

[Link](quarters + "quarters");

• Where:
• System is a standard class
• out is an object that is part of Java.
• println() is one of the methods available to the

13
Screen Output

• Syntax to use println


[Link] (Output_1 + Output_2 + … +
Output_Last);

• The concatenation operator (+) is useful when everything does


not fit on one line.
[Link]("Lucky number = " + 13
+"Secret number = " + number);
the output will be
Lucky number = 13Secret number = 7 Note, for readability, you
should break the line
before or
after a + operator, and you
should indent
14
the continuation line.
Screen Output

• You can also use the println method to display the value of a
String variable

• Example:
String greeting = "Hello Programmers!";
[Link](greeting);

This will cause the following to be written on the screen:


Hello Programmers!

15
Screen Output
• Every invocation of println ends a line of output i.e. it
inserts a new line!

• Alternatively, use print()


[Link]("One, two,");
[Link](" buckle my shoe.");
[Link](" Three, four,");
[Link](" shut the door.");

produces the following output:


One, two, buckle my shoe. Three, four,
shut the door.

16
Escape Characters

• How would you print "Java" refers to a


language.?

• The compiler needs to be told that the quotation marks (")


do not signal the start or end of a string, but instead are to
be printed.

• We use \ before an escape character


[Link]("\"Java\" refers to a language.");

17
Escape Characters

• Each escape sequence is a single character even though it is


written with two symbols.

18
Printing Escape Characters Examples

[Link]("abc\\def"); abc\def

new
[Link]("new\nline");
line

char singleQuote = '\'';


'
[Link]
(singleQuote);

19
Formatted Output with printf ( )
• printf works like the print method except it allows you to add formatting
instructions that specify things such as the number of digits to include after a
decimal point.
format
• Syntax,
[Link](%[specifier>][Flag][width][.precision]specifier,argument);
The format can include:
• specifier: These are marked with % followed by a character that indicates the type of
argument.
• For example, %d for integers, %f for floating-point numbers, %s for strings, etc.
• Flags: These are optional characters that modify the formatting, like - for left-justification, +
for always showing a sign, 0 for padding with zeros, etc.
• Width: An optional integer specifying the minimum field width.
• Precision: An optional integer specifying the number of digits after the decimal point for
floating-point numbers.

20
Common Format Specifiers

21
printf ( ) vs print()
• printf works like the print method except it allows you to add
formatting instructions that specify things such as the number of
digits to include after a decimal point.
• Example,
double price = 19.5;
[Link]("Price using println:" + price);
[Link]("Price using printf formatting:%6.2f", price);

The format specifier %6.2f


This code outputs the following lines: says to output a floating-point
Price using println:19.5 number in a field (number of
Price using printf formatting: 19.50 spaces) of width six (room for
six characters) and to
show exactly two digits after
the decimal point. So, 19.5 is
expressed as "19.50" in
a field of width six.
22
flags

• Flags modify the overall appearance of the output. Here are some
common flags:

double price = 19.99;


[Link]("%+10.2f \n", price); // Output: +19.99
[Link]("%010.2f \n", price); // Output: 0000019.99
[Link]("%-10.2f \n", price); // Output: 19.99

+: Forces the display of a sign (+ or -) for numeric values.


0: Pads the output with zeros instead of spaces to fill the specified field
width.
-: Left-justifies the output within the specified field width.
Makes the output left-justified by adding any padding spaces to the right instead of to the
left.

23
width

• The width specifies the minimum number of characters to be printed.


• If the actual value is shorter, it will be padded with spaces or zeros
(depending on the flags) to reach the specified width.
• Example

int number = 123;


[Link]("%10d\n", number); // Output:_____123
[Link]("%-10d\n", number); // Output: 123_____

• %10d: This formats the number with a minimum width of 10 characters, right-justified.
• %-10d: This formats the number with a minimum width of 10 characters, left-justified.

24
Examples

25
Examples

26
Common Format Specifiers Example
double price = 19.5;
int quantity = 2;
String item = "Widgets";

[Link]("%10s sold:%4d at $%5.2f. Total =


$%1.2f", item, quantity, price, quantity * price);

the output is:


Widgets sold: 2 at $19.50. Total = $39.00

• %10s: A string (item) is formatted with a minimum width of 10 characters, left-justified.


• sold:%4d: The string "sold:" is printed, followed by an integer (quantity) formatted with a
minimum width of 4 characters.
• at $%5.2f: The string "at $" is printed, followed by a floating-point number (price)
formatted with a minimum width of 5 characters and 2 decimal places.
• . Total = $%1.2f: The string ". Total = $" is printed, followed by a floating-point number
(quantity * price) formatted with a minimum width of 1 character and 2 decimal places.

27
Show the exact output produced by the following
println methods:

int counter = 5;
[Link]("counter = " + counter++);

counter = 5
[Link]("counter = " + counter%2);

counter = 0

28

You might also like