Java program ने फक्त fixed values वर काम करणे पुरेसे नसते. Real application मध्ये data अनेकदा user कडून runtime ला येतो—उदा. नाव, age, salary, marks, quantity, price किंवा menu choice.
या chapter मध्ये आपण Java console application मध्ये user कडून input कसा घ्यायचा हे शिकणार आहोत: Scanner Class, Integer, Decimal, String, Character आणि common Scanner problems.
या chapter मधील examples Java SE 26 च्या Scanner API शी compatible आहेत. Scanner text input ला tokens मध्ये divide करू शकतो आणि त्या tokens ना int, double सारख्या values मध्ये parse करू शकतो.
Learning Outcomes#
हा chapter पूर्ण केल्यानंतर तुम्ही independently:
Scannerobject create करून console input घेऊ शकाल.nextInt()वापरून integer read करू शकाल.nextDouble()वापरून decimal value read करू शकाल.next()आणिnextLine()मधील फरक explain करू शकाल.- full name किंवा spaces असलेला text योग्य पद्धतीने read करू शकाल.
- Java मध्ये direct
nextChar()method का नाही हे explain करू शकाल. next().charAt(0)वापरून character read करू शकाल.nextInt()नंतरnextLine()वापरताना येणारा common problem identify आणि fix करू शकाल.- invalid numeric input मुळे
InputMismatchExceptionका येऊ शकते हे ओळखू शकाल. - एका console program मध्ये एकच reusable
Scannerठेवण्याचे कारण explain करू शकाल. - basic Scanner-related interview questions confidently answer करू शकाल.
1. User Input म्हणजे काय?#
User input is data provided to a program by a user while the program is running.
Program execute होत असताना user program ला जी माहिती देतो तिला user input म्हणतात.
उदाहरण:
Enter your name: Rahul
Enter your age: 24
Enter course price: 4999.50येथे:
Rahul→ String input24→ integer input4999.50→ decimal input
Program आधीच या values जाणत नाही.
User program run करताना values provide करतो.
Fixed value#
int age = 24;येथे 24 source code मध्ये fixed आहे.
User input#
int age = scanner.nextInt();येथे value runtime ला user कडून मिळते.
यामुळे एकच program वेगवेगळ्या users च्या वेगवेगळ्या values वर काम करू शकतो.
2. Scanner Class#
Scanner is a Java class used to read and parse text input from sources such as the console, strings, or files.
Scanner ही Java मधील class आहे जी input read करण्यासाठी आणि त्या input ला आवश्यक data type मध्ये convert करण्यासाठी वापरता येते.
Beginner console applications मध्ये आपण मुख्यतः:
Scanner scanner = new Scanner(System.in);हा pattern वापरणार आहोत.
Scanner वापरण्याची basic structure#
import java.util.Scanner;
public class UserInputDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Welcome " + name);
}
}Possible Run#
Enter your name: Rahul Patil
Welcome Rahul Patilimport java.util.Scanner; म्हणजे काय?#
Scanner class java.util package मध्ये आहे.
त्यामुळे source file मध्ये आपण लिहितो:
import java.util.Scanner;यानंतर आपण short name:
Scannerवापरू शकतो.
या chapter साठी package system deeply शिकण्याची गरज नाही. सध्या एवढे लक्षात ठेवा:
Scannerवापरायचा असेल तर सामान्यतःimport java.util.Scanner;आवश्यक आहे.
3. Scanner Object समजून घेऊ#
ही line पहा:
Scanner scanner = new Scanner(System.in);ती एकदम memorize करू नका.
तिचा basic अर्थ समजा.
Scanner#
Object चा type.
scanner#
आपण object ला दिलेले variable name.
हे नाव काहीही technically valid असू शकते:
Scanner input = new Scanner(System.in);किंवा:
Scanner sc = new Scanner(System.in);पण readable code साठी:
scannerहे चांगले descriptive नाव आहे.
new Scanner(...)#
नवीन Scanner object create करतो.
System.in#
Standard input source दर्शवतो.
आपल्या console program मध्ये सामान्यतः हा input keyboard वरून येतो.
Simple Mental Model#
Keyboard
↓
System.in
↓
Scanner
↓
nextInt() / nextDouble() / next() / nextLine()
↓
Java Variableउदाहरण:
int age = scanner.nextInt();Flow:
User types 25
↓
Scanner reads 25
↓
nextInt() interprets it as int
↓
age = 254. Scanner Input Methods#
आपण या chapter मध्ये मुख्य methods वापरणार आहोत:
| Requirement | Scanner Method |
|---|---|
| Integer | nextInt() |
| Decimal | nextDouble() |
| Single word | next() |
| Complete line | nextLine() |
| Character | direct Scanner method नाही |
| First character of next token | next().charAt(0) |
Scanner मध्ये nextInt(), nextDouble(), next() आणि nextLine() यांसारखे methods उपलब्ध आहेत. next() delimiter-separated token read करतो, तर nextLine() current line मधील उरलेला text line separator पर्यंत read करतो.
5. Reading Integer#
nextInt() reads the next input token as an int value.
nextInt() user कडून आलेल्या पुढच्या valid integer token ला int म्हणून read करतो.
Example: Age Input#
import java.util.Scanner;
public class AgeInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your age: ");
int age = scanner.nextInt();
System.out.println("Your age is " + age);
}
}Possible Run#
Enter your age: 25
Your age is 25Important Line#
int age = scanner.nextInt();येथे दोन operations होत आहेत:
scanner.nextInt()
↓
user कडून integer read
↓
returned int value
↓
age variable मध्ये storeReal Example: Product Quantity#
Suppose billing application मध्ये customer किती items घेणार आहे हे विचारायचे आहे.
import java.util.Scanner;
public class ProductQuantity {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter product quantity: ");
int quantity = scanner.nextInt();
System.out.println("Selected quantity: " + quantity);
}
}Possible Run#
Enter product quantity: 4
Selected quantity: 46. nextInt() ला काय input अपेक्षित आहे?#
जर program लिहिला:
int age = scanner.nextInt();आणि user ने input दिले:
30तर योग्य.
पण user ने दिले:
thirtyतर Scanner त्या token ला valid int म्हणून interpret करू शकत नाही.
त्यामुळे:
InputMismatchExceptionयेऊ शकते.
InputMismatchException indicates that the input token does not match the type expected by the Scanner method.
म्हणजे Scanner ज्या प्रकारची value अपेक्षित करत आहे, input त्या format मध्ये नाही.
उदा.:
nextInt() expects integer
User enters: helloResult:
InputMismatchExceptionnextInt() ला पुढचा token valid integer म्हणून parse करता आला नाही किंवा value int range बाहेर असेल तर InputMismatchException throw होऊ शकते.
या chapter मध्ये exception handling deeply शिकणार नाही. सध्या error चे कारण identify करता आले पाहिजे.
7. Reading Decimal Value#
Real applications मध्ये अनेक values decimal असतात:
- price
- percentage
- temperature
- weight
- height
- rating
त्यासाठी आपण nextDouble() वापरू शकतो.
nextDouble()#
nextDouble() reads the next input token as a double value.
nextDouble() पुढचा numeric token decimal-capable double value म्हणून read करतो.
Example: Product Price#
import java.util.Scanner;
public class PriceInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter product price: ");
double price = scanner.nextDouble();
System.out.println("Product price: " + price);
}
}Possible Run#
Enter product price: 1499.50
Product price: 1499.5तुम्ही input:
1499.50दिलात तरी double value print करताना:
1499.5दिसू शकते.
कारण numeric value म्हणून trailing zero display करण्याची आवश्यकता नसते.
Example: Temperature#
import java.util.Scanner;
public class TemperatureInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter temperature: ");
double temperature = scanner.nextDouble();
System.out.println("Recorded temperature: " + temperature);
}
}Possible Run#
Enter temperature: 36.7
Recorded temperature: 36.7Integer आणि Decimal फरक#
int quantity = scanner.nextInt();
double price = scanner.nextDouble();| Input | Appropriate Type |
|---|---|
5 items | int |
99.50 price | double |
18 age | int |
72.4 weight | double |
Data type requirement वरून method निवडा.
Method फक्त "number" पाहून निवडू नका.
Good to Know: Decimal Format and Locale#
Scanner numeric parsing locale-sensitive असू शकते.
Beginner examples मध्ये आपण:
99.50या familiar decimal format वर काम करू.
Real international applications मध्ये numeric separators locale नुसार बदलू शकतात. Scanner मध्ये locale configuration support आहे, पण ते या beginner chapter च्या scope बाहेर आहे.
8. Reading String#
String input मध्ये एक मोठा beginner confusion असतो:
next()आणि
nextLine()दोन्ही String return करतात, पण दोघांचे behavior वेगळे आहे.
9. next() Method#
next() reads the next complete token, normally separated by whitespace.
Default configuration मध्ये Scanner whitespace ला delimiter म्हणून वापरतो. त्यामुळे next() साधारणपणे पुढचा एक token read करतो.
उदाहरण:
Rahul Patilजर code:
String name = scanner.next();असेल तर result:
Rahulहोऊ शकतो.
Patil हा पुढचा वेगळा token राहतो.
Example#
import java.util.Scanner;
public class FirstNameInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your first name: ");
String firstName = scanner.next();
System.out.println("Hello " + firstName);
}
}Possible Run#
Enter your first name: Rahul
Hello RahulSingle-word input साठी next() useful आहे.
10. nextLine() Method#
nextLine() reads the remaining content of the current line and advances the Scanner to the next line.
nextLine() current line मधील उरलेला text read करतो आणि line separator consume करून scanner पुढच्या line च्या सुरुवातीला नेतो.
Full name, address, sentence, message यांसारख्या spaces असलेल्या input साठी हे विशेष useful आहे.
Example: Full Name#
import java.util.Scanner;
public class FullNameInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your full name: ");
String fullName = scanner.nextLine();
System.out.println("Welcome " + fullName);
}
}Possible Run#
Enter your full name: Rahul Sanjay Patil
Welcome Rahul Sanjay Patil11. next() vs nextLine()#
हा फरक खूप महत्त्वाचा आहे.
| Feature | next() | nextLine() |
|---|---|---|
| Return type | String | String |
| Reads | next token | remaining complete line |
| Spaces inside text | साधारणपणे नाही | हो |
| Good for | username, city code, simple word | full name, address, sentence |
Example Input#
User types:
Dattatray SabneUsing next()#
String name = scanner.next();Result:
DattatrayUsing nextLine()#
String name = scanner.nextLine();Result:
Dattatray SabneDecision Rule#
Requirement:
Enter username
Possible input:
dattatraynext() योग्य असू शकतो.
Requirement:
Enter full name
Possible input:
Dattatray SabnenextLine() योग्य.
Requirement आधी समजा, method नंतर निवडा.
12. Reading Character#
Java beginner ला naturally वाटते:
scanner.nextChar()असे काहीतरी असावे.
पण Scanner मध्ये direct:
nextChar()method नाही.
Character म्हणजे काय?#
A char stores a single UTF-16 code unit and is commonly used for a single character value in beginner Java programs.
Beginner level वर char म्हणजे एक single character value store करण्यासाठी वापरला जाणारा primitive type असे समजू शकतो.
उदाहरण:
char grade = 'A';13. Scanner मधून Character कसा घ्यायचा?#
Common beginner pattern:
char grade = scanner.next().charAt(0);हे दोन steps मध्ये समजा.
Step 1#
scanner.next()String token read करतो.
जर user input:
Aतर मिळते:
"A"Step 2#
.charAt(0)String मधील index 0 वरचा character घेतो.
Result:
'A'Full Example#
import java.util.Scanner;
public class GradeInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your grade: ");
char grade = scanner.next().charAt(0);
System.out.println("Your grade is " + grade);
}
}Possible Run#
Enter your grade: A
Your grade is AWhy index 0?#
String:
JavaIndexes:
J a v a
0 1 2 3म्हणून:
"Java".charAt(0)Result:
Jजर user ने Male type केले तर?#
char value = scanner.next().charAt(0);Input:
MaleResult:
Mकारण आपण first token चा first character घेत आहोत.
यामुळे requirement clear असणे गरजेचे आहे.
जर requirement single character असेल:
Enter section: Auser ला ते UI prompt मधून स्पष्ट करा.
14. Complete Example — Multiple Inputs#
आता integer, decimal, String आणि character एकत्र वापरू.
Requirement:
Student कडून घ्या:
- full name
- age
- percentage
- section
एक important problem येणार असल्यामुळे input order विचारपूर्वक ठेवू.
import java.util.Scanner;
public class StudentInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter full name: ");
String name = scanner.nextLine();
System.out.print("Enter age: ");
int age = scanner.nextInt();
System.out.print("Enter percentage: ");
double percentage = scanner.nextDouble();
System.out.print("Enter section: ");
char section = scanner.next().charAt(0);
System.out.println();
System.out.println("Student Details");
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Percentage: " + percentage);
System.out.println("Section: " + section);
}
}Possible Run#
Enter full name: Rahul Patil
Enter age: 22
Enter percentage: 78.5
Enter section: A
Student Details
Name: Rahul Patil
Age: 22
Percentage: 78.5
Section: A15. Common Scanner Problem — nextInt() नंतर nextLine()#
हा Scanner चा सर्वात famous beginner problem आहे.
Code पहा:
import java.util.Scanner;
public class ScannerProblem {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter age: ");
int age = scanner.nextInt();
System.out.print("Enter full name: ");
String name = scanner.nextLine();
System.out.println("Age: " + age);
System.out.println("Name: " + name);
}
}User:
Enter age: 25type करून Enter press करतो.
नंतर program full name input "skip" केल्यासारखा वाटू शकतो.
Problem का होतो?#
User types:
25↵Conceptually input मध्ये:
25 + line separatorअसतो.
nextInt():
scanner.nextInt();integer token:
25read करतो.
Scanner ची position integer नंतर असते.
नंतर:
scanner.nextLine();current line चा remaining portion read करतो.
25 नंतर त्या current line मध्ये text उरलेला नसल्यामुळे nextLine() empty string return करून line separator consume करू शकतो.
यामुळे name विचारल्यावर user ला input देण्याची संधी मिळाली नाही असे वाटते.
nextLine() च्या documented behavior नुसार ते current line मधील remaining input return करून scanner ला पुढच्या line च्या सुरुवातीला नेते.
16. Fix — Pending Line Consume करा#
int age = scanner.nextInt();
scanner.nextLine();
String name = scanner.nextLine();पहिला:
scanner.nextLine();previous numeric input नंतर उरलेली line consume करतो.
दुसरा:
scanner.nextLine();actual full name read करतो.
Correct Example#
import java.util.Scanner;
public class ScannerFix {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter age: ");
int age = scanner.nextInt();
scanner.nextLine();
System.out.print("Enter full name: ");
String name = scanner.nextLine();
System.out.println("Age: " + age);
System.out.println("Name: " + name);
}
}Possible Run#
Enter age: 25
Enter full name: Rahul Patil
Age: 25
Name: Rahul Patil17. हा Problem फक्त nextInt() मुळेच आहे का?#
नाही.
General issue म्हणजे token-oriented methods आणि nextLine() mix करणे.
उदाहरणार्थ:
nextInt()
nextDouble()
next()हे token-oriented operations आहेत.
तर:
nextLine()line-oriented आहे.
विशेषतः numeric method नंतर लगेच nextLine() घेताना current line मध्ये काय उरले आहे ते विचार करा.
18. Better Mental Model: Token vs Line#
Input:
25 Rahul PatilScanner कडे दोन वेगळ्या दृष्टीने पाहू शकतो.
Token View#
Default whitespace delimiter असल्यामुळे:
Token 1 → 25
Token 2 → Rahul
Token 3 → PatilLine View#
Line 1 → 25 Rahul PatilnextInt(), next(), nextDouble() सारखे methods token-based parsing करतात.
nextLine() line चा remaining भाग पाहतो.
हा फरक समजला की Scanner चे बरेच confusion आपोआप कमी होते.
19. Common Problem — Wrong Data Type#
Code:
int age = scanner.nextInt();Input:
twenty fiveScanner ला हा token int मध्ये parse करता येत नाही.
Possible result:
InputMismatchExceptionMistake#
User कडून कोणतीही value येऊ शकते हे ignore करणे.
Root Cause#
Program integer expect करतो पण input integer format मध्ये नाही.
Prevention#
पुढे control-flow आणि validation concepts शिकल्यानंतर input validate करता येईल.
Scanner मध्ये hasNextInt() सारखी checking methods आहेत, पण decision-making syntax आपला पुढचा chapter असल्यामुळे ते येथे implementation-level detail मध्ये शिकवत नाही. hasNextInt() पुढचा token valid int आहे का हे scanner advance न करता check करू शकते.
20. Common Problem — next() वापरून Full Name घेणे#
Requirement:
Enter your full nameCode:
String name = scanner.next();User:
Rahul Sanjay PatilVariable मध्ये:
Rahulइतकेच येते.
Root Cause#
next() पुढचा token read करतो.
Better Approach#
String name = scanner.nextLine();21. Common Problem — nextChar() वापरणे#
Wrong:
char grade = scanner.nextChar();Scanner मध्ये असा method उपलब्ध नाही.
Better#
char grade = scanner.next().charAt(0);22. Common Problem — चुकीचा charAt() index#
Code:
char grade = scanner.next().charAt(1);Input:
AString length फक्त 1 आहे.
Valid index:
01 नाही.
Single-character token साठी:
char grade = scanner.next().charAt(0);वापरा.
23. Common Problem — अनेक Scanner Objects#
Beginner कधी कधी प्रत्येक input साठी नवीन object create करतो:
Scanner scanner1 = new Scanner(System.in);
Scanner scanner2 = new Scanner(System.in);
Scanner scanner3 = new Scanner(System.in);Basic console application साठी हे unnecessary आहे.
Prefer:
Scanner scanner = new Scanner(System.in);आणि तोच object reuse करा:
int age = scanner.nextInt();
double salary = scanner.nextDouble();
String city = scanner.next();Why Better?#
- code simpler राहतो
- input flow समजायला सोपा होतो
- same underlying
System.inवर unnecessary multiple wrappers टाळता येतात
24. Scanner Close करायचा का?#
Scanner Closeable आहे आणि त्याला close() method आहे.
उदाहरण:
scanner.close();पण एक important practical point आहे:
Scanner scanner = new Scanner(System.in);हा Scanner System.in wrap करतो.
Scanner close केल्यावर underlying input source सुद्धा close होऊ शकतो. त्यामुळे program मध्ये पुढे console input आवश्यक असेल तर Scanner लवकर close करू नका.
Beginner rule:
One console Scanner तयार करा, पूर्ण input flow मध्ये reuse करा आणि program ला input ची आवश्यकता संपण्यापूर्वी तो close करू नका.
25. Practical / Real-World Application#
Scenario: Course Registration Console#
Requirement:
Training application ला student कडून खालील data घ्यायचा आहे:
- full name
- age
- selected course
- course fee
- batch code
Analysis#
| Data | Type | Input Method |
|---|---|---|
| Full name | String | nextLine() |
| Age | int | nextInt() |
| Course | String | next() or nextLine() |
| Fee | double | nextDouble() |
| Batch code | char | next().charAt(0) |
जर course नाव:
Javaअसेल तर next() पुरेसे असू शकते.
पण:
Java Beginner Courseअसेल तर nextLine() आवश्यक आहे.
Requirement method ठरवते.
Implementation#
import java.util.Scanner;
public class CourseRegistration {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter full name: ");
String fullName = scanner.nextLine();
System.out.print("Enter age: ");
int age = scanner.nextInt();
System.out.print("Enter course fee: ");
double courseFee = scanner.nextDouble();
System.out.print("Enter batch code: ");
char batchCode = scanner.next().charAt(0);
scanner.nextLine();
System.out.print("Enter course name: ");
String courseName = scanner.nextLine();
System.out.println();
System.out.println("Registration Details");
System.out.println("Name: " + fullName);
System.out.println("Age: " + age);
System.out.println("Course: " + courseName);
System.out.println("Fee: " + courseFee);
System.out.println("Batch: " + batchCode);
}
}Possible Run#
Enter full name: Snehal Mohite
Enter age: 24
Enter course fee: 4999.50
Enter batch code: A
Enter course name: Java Beginner Course
Registration Details
Name: Snehal Mohite
Age: 24
Course: Java Beginner Course
Fee: 4999.5
Batch: AProfessional Reasoning#
कोणता Scanner method वापरायचा हे syntax question नाही.
ते data requirement question आहे.
Developer ने विचारले पाहिजे:
या field मध्ये कोणत्या प्रकारची value येणार?
↓
Number की Text?
↓
Text असल्यास spaces असतील का?
↓
Single character आहे का?
↓
योग्य Scanner method निवडाही reasoning real development मध्ये syntax memorize करण्यापेक्षा जास्त useful आहे.
26. Common Mistakes & Misconceptions#
Misconception 1: next() आणि nextLine() same आहेत#
Why it sounds believable#
दोन्ही String return करतात.
Correct Understanding#
next() token read करतो.
nextLine() current line मधील remaining text read करतो.
Misconception 2: Scanner मध्ये nextChar() असणारच#
Why it sounds believable#
आपल्याकडे:
nextInt()
nextDouble()आहेत.
म्हणून naturally:
nextChar()असेल असे वाटते.
Correct Understanding#
Scanner मध्ये direct nextChar() नाही.
Common beginner approach:
scanner.next().charAt(0);Misconception 3: nextInt() Enter key सुद्धा पूर्णपणे handle करतो#
Why it sounds believable#
User number type करून Enter press करतो आणि number successfully read होतो.
Correct Understanding#
nextInt() integer token parse करतो. त्यानंतर लगेच nextLine() वापरल्यास current line चा remaining भाग empty असू शकतो आणि nextLine() तो consume करून empty string return करू शकतो.
Misconception 4: User ने काहीही type केले तरी Scanner convert करेल#
Wrong assumption:
scanner.nextInt();Input:
twentyScanner magically 20 बनवेल.
असे होत नाही.
Input expected format मध्ये असणे आवश्यक आहे.
Misconception 5: प्रत्येक input साठी नवीन Scanner हवा#
नाही.
सामान्य console program मध्ये एक Scanner object तयार करून reuse करणे cleaner आहे.
Misconception 6: nextDouble() म्हणजे फक्त decimal point असलेली value#
नाही.
Input:
100हे सुद्धा double म्हणून parse होऊ शकते आणि value:
100.0म्हणून represent होऊ शकते.
Method निवडताना input च्या business meaning कडे बघा.
27. Hands-On Practice#
Practice 1 — Employee Age#
Requirement#
User कडून employee age घ्या आणि print करा.
Learner Task#
Output pattern:
Enter employee age: 30
Employee age: 30Hint 1#
Age whole number आहे.
Hint 2#
Use:
nextInt()Solution#
import java.util.Scanner;
public class EmployeeAge {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter employee age: ");
int age = scanner.nextInt();
System.out.println("Employee age: " + age);
}
}Practice 2 — Product Price#
Requirement#
Product price user कडून घ्या.
Example#
Enter price: 749.50
Price: 749.5Hint#
Use a decimal-capable type.
Solution#
import java.util.Scanner;
public class ProductPrice {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter price: ");
double price = scanner.nextDouble();
System.out.println("Price: " + price);
}
}Practice 3 — Full Name#
Requirement#
Spaces असलेले full name read करा.
Input#
Rahul Ashok PatilWrong Choice#
scanner.next();Hint#
Complete line हवी आहे.
Solution#
import java.util.Scanner;
public class FullName {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter full name: ");
String fullName = scanner.nextLine();
System.out.println("Full name: " + fullName);
}
}Practice 4 — Grade#
Requirement#
User कडून single grade character घ्या.
Input:
AHint#
Scanner मध्ये direct nextChar() नाही.
Solution#
import java.util.Scanner;
public class GradeInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter grade: ");
char grade = scanner.next().charAt(0);
System.out.println("Grade: " + grade);
}
}Practice 5 — Find and Fix#
Problematic code:
import java.util.Scanner;
public class UserDetails {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter age: ");
int age = scanner.nextInt();
System.out.print("Enter full name: ");
String name = scanner.nextLine();
System.out.println(name);
}
}Learner Task#
Name input skip का होतो ते explain करा आणि code fix करा.
Hint#
nextInt() नंतर current line मध्ये काय उरले आहे?
Solution#
import java.util.Scanner;
public class UserDetails {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter age: ");
int age = scanner.nextInt();
scanner.nextLine();
System.out.print("Enter full name: ");
String name = scanner.nextLine();
System.out.println("Age: " + age);
System.out.println("Name: " + name);
}
}Explanation#
Extra:
scanner.nextLine();previous numeric input च्या line मधील remaining part consume करते.
त्यानंतर next nextLine() actual full name read करते.
28. Interview Preparation#
1. What is the Scanner class in Java?
Scanner is a class in the java.util package that can read and parse text input from different sources. In beginner console applications, it is commonly used with System.in to read user input.
What the interviewer is testing: Whether you understand the purpose of Scanner, not merely its syntax.
2. How do you create a Scanner to read console input?
Scanner scanner = new Scanner(System.in);You normally import it using:
import java.util.Scanner;3. Which Scanner method is commonly used to read an integer?
nextInt().
Example:
int age = scanner.nextInt();It attempts to parse the next token as an int.
4. Which Scanner method is used to read a double value?
nextDouble().
Example:
double price = scanner.nextDouble();5. What is the difference between next() and nextLine()?
next() reads the next complete token based on the Scanner's delimiter pattern. With the default delimiter, whitespace separates tokens.
nextLine() reads the remaining content of the current line and moves the Scanner to the beginning of the next line.
For example, for the input:
Rahul Patilnext() normally returns:
Rahulwhile nextLine() can return:
Rahul PatilCommon weak answer: “next() reads one word and nextLine() reads many words.”
That is useful as a beginner shortcut but the technically stronger explanation is based on tokens versus the remaining line.
6. How can you read a character using Scanner?
Scanner does not provide a direct nextChar() method.
A common approach is:
char grade = scanner.next().charAt(0);next() reads a String token and charAt(0) retrieves its first character.
7. Does Scanner have a nextChar() method?
No.
A common beginner technique is:
scanner.next().charAt(0);8. Why can nextLine() appear to be skipped after nextInt()?
nextInt() parses the integer token but does not behave like nextLine(), which consumes the remaining content of the current line.
After the integer is entered, the Scanner may still be positioned before the end of that line. A following nextLine() can therefore read the empty remainder of that line and immediately return an empty String.
A common fix is:
int age = scanner.nextInt();
scanner.nextLine();
String name = scanner.nextLine();9. What happens when nextInt() receives non-integer input?
If the next token cannot be interpreted as a valid int, nextInt() can throw an InputMismatchException.
For example:
Expected: 25
Entered: twenty-five10. When would you prefer nextLine() over next()?
Use nextLine() when the requirement is to read an entire line that may contain spaces, such as:
- full name
- address
- sentence
- description
- message
Use next() when one delimiter-separated token is appropriate.
11. Should you create a new Scanner for every input?
Normally, no.
For a simple console program, create one Scanner connected to System.in and reuse it for the input flow.
This keeps the program simpler and avoids unnecessary multiple wrappers over the same input source.
12. Why should you be careful when closing a Scanner created with System.in?
Closing the Scanner also closes its underlying input source. If that source is System.in, later attempts to read console input can fail.
Therefore, do not close it before the application has finished using console input.
13. What is a token in Scanner?
A token is a unit of input separated according to the Scanner's delimiter pattern.
By default, Scanner uses whitespace as its delimiter.
For example:
Java Beginner Courseis normally seen as three tokens:
Java
Beginner
Course14. Can nextDouble() read the input 100?
Yes.
A whole-number token such as 100 can represent a valid double value and may be returned as:
100.029. Quick Revision#
Create Scanner#
Scanner scanner = new Scanner(System.in);Import:
import java.util.Scanner;Integer#
int age = scanner.nextInt();Decimal#
double price = scanner.nextDouble();Single Token#
String username = scanner.next();Complete Line#
String fullName = scanner.nextLine();Character#
char grade = scanner.next().charAt(0);Important Difference#
next() → next token
nextLine() → remaining current lineFamous Scanner Problem#
Problem:
int age = scanner.nextInt();
String name = scanner.nextLine();Better:
int age = scanner.nextInt();
scanner.nextLine();
String name = scanner.nextLine();Invalid Integer Input#
scanner.nextInt();आणि input:
helloअसल्यास:
InputMismatchExceptionयेऊ शकते.
30. You Should Now Be Able To#
तुम्हाला आता independently:
Scannerम्हणजे काय हे explain करता आले पाहिजे.Scannerconsole input शी connect करता आले पाहिजे.nextInt()वापरता आले पाहिजे.nextDouble()वापरता आले पाहिजे.next()आणिnextLine()compare करता आले पाहिजे.- spaces असलेला String योग्य method ने read करता आला पाहिजे.
- character input घेता आला पाहिजे.
- direct
nextChar()नसल्याचे explain करता आले पाहिजे. nextInt()+nextLine()issue diagnose करता आला पाहिजे.InputMismatchExceptionचे basic कारण identify करता आले पाहिजे.- requirement नुसार योग्य Scanner method निवडता आला पाहिजे.
31. Final Challenge#
Scenario#
तुम्ही एक छोटा Employee Registration Console Program तयार करत आहात.
User कडून घ्यायचे आहे:
Employee ID
Full Name
Salary
Department Name
Performance GradeData Requirements#
Employee ID → whole number
Full Name → spaces allowed
Salary → decimal allowed
Department Name → spaces allowed
Performance Grade → one characterLearner Task#
योग्य:
- Java data types
- Scanner methods
- input order
nextLine()handling
निवडून complete program तयार करा.
Hints#
Hint 1#
Employee ID:
nextInt()Hint 2#
ID read केल्यानंतर full name घ्यायचे आहे.
Token-to-line transition लक्षात ठेवा.
Hint 3#
Salary:
nextDouble()Hint 4#
Salary नंतर department चे full text घ्यायचे असल्यामुळे पुन्हा line transition विचारात घ्या.
Hint 5#
Grade:
next().charAt(0)Solution#
import java.util.Scanner;
public class EmployeeRegistration {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter employee ID: ");
int employeeId = scanner.nextInt();
scanner.nextLine();
System.out.print("Enter full name: ");
String fullName = scanner.nextLine();
System.out.print("Enter salary: ");
double salary = scanner.nextDouble();
scanner.nextLine();
System.out.print("Enter department name: ");
String department = scanner.nextLine();
System.out.print("Enter performance grade: ");
char grade = scanner.next().charAt(0);
System.out.println();
System.out.println("Employee Registration");
System.out.println("ID: " + employeeId);
System.out.println("Name: " + fullName);
System.out.println("Salary: " + salary);
System.out.println("Department: " + department);
System.out.println("Grade: " + grade);
}
}Possible Run#
Enter employee ID: 101
Enter full name: Rahul Sanjay Patil
Enter salary: 65000.50
Enter department name: Software Development
Enter performance grade: A
Employee Registration
ID: 101
Name: Rahul Sanjay Patil
Salary: 65000.5
Department: Software Development
Grade: AReasoning#
Employee ID साठी:
nextInt()Salary साठी:
nextDouble()Full name आणि department मध्ये spaces येऊ शकतात म्हणून:
nextLine()Performance grade single character असल्यामुळे:
next().charAt(0)आणि numeric input वरून nextLine() कडे transition होताना pending line consume करण्यासाठी:
scanner.nextLine();वापरले आहे.