Reading numbers, words and characters
18 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)Scanner has a separate reading method for each type of value: nextInt() for a whole number, nextDouble() for a decimal, next() for one word, and a small trick for one character.
One method for each type
A petrol bill needs litres like 5.5, but nextInt() stops the program on it: an int cannot hold a decimal point.
Each Scanner method reads one type: pick the one that matches your variable, such as nextDouble() for a double.
Example 1 · Petrol bill with nextDouble()
import java.util.Scanner;
public class PetrolBill { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Litres: "); double litres = sc.nextDouble(); System.out.print("Price per litre: "); double price = sc.nextDouble(); System.out.printf("Bill: Rs. %.2f%n", litres * price); sc.close(); }}Litres: 5.5 Price per litre: 102 Bill: Rs. 561.00
What this code does
nextDouble()reads5.5into adouble.- The user typed the whole number
102;nextDouble()accepts it as102.0. %.2ffrom Formatted output (opens in a new tab) prints the bill with two decimals.
The others work the same way: nextInt() for an int, nextLong() for very big whole numbers, nextBoolean() for true or false, next() for one word and nextLine() for the whole line. Match some typed values to their method below.
Classify
Which method reads it?
Tap a value the user will type, then tap the method that should read it.
Several values on one line
People often type three marks on one line, 85 90 78, instead of pressing Enter after each.
Scanner splits the input at spaces and at Enter; each piece is a token. nextInt(), nextDouble() and next() each take one token: a waiting one at once, or else they wait for the user. Step through it below.
Trace the code
Three marks arrive one by one
Variables
None yet.
Output
Enter 3 marks:
Typed input: 85 90 78
Line 6The prompt asks for all three marks on one line.
nextInt() simply waits for its token.Reading one character
A form asks for a grade like A, and you want it in a char, but Scanner has no nextChar() method.
Read a word with next(), then take its first character with charAt(0).
Example 2 · A word and a character
import java.util.Scanner;
public class Grade { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter your first name: "); String first = sc.next(); System.out.print("Enter your grade: "); char grade = sc.next().charAt(0); System.out.println(first + " got grade " + grade); sc.close(); }}Enter your first name: Arjun Enter your grade: A Arjun got grade A
What this code does
next()reads one word,Arjun.sc.next()readsAas a String, andcharAt(0)takes its first character as achar.
Java counts positions from 0, so position 0 is the first character. Essential String methods (opens in a new tab) covers charAt fully.
Next step
Check your understanding
8 quick questions