CodeLangs AISoftware Training Institute
Java for Beginners (Marathi)/User Input
Dashboard
Chapter 10 · Java for Beginners

User Input

3,690
words
17
min read
30
practice items
Interactive learning

Practice lab

Question 1 of 16 00:00

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:

  • Scanner object 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 म्हणतात.

उदाहरण:

TEXT
Enter your name: Rahul
Enter your age: 24
Enter course price: 4999.50

येथे:

  • Rahul → String input
  • 24 → integer input
  • 4999.50 → decimal input

Program आधीच या values जाणत नाही.

User program run करताना values provide करतो.

Fixed value#

JAVA
int age = 24;

येथे 24 source code मध्ये fixed आहे.

User input#

JAVA
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 मध्ये आपण मुख्यतः:

JAVA
Scanner scanner = new Scanner(System.in);

हा pattern वापरणार आहोत.


Scanner वापरण्याची basic structure#

JAVA
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#

TEXT
Enter your name: Rahul Patil
Welcome Rahul Patil

import java.util.Scanner; म्हणजे काय?#

Scanner class java.util package मध्ये आहे.

त्यामुळे source file मध्ये आपण लिहितो:

JAVA
import java.util.Scanner;

यानंतर आपण short name:

JAVA
Scanner

वापरू शकतो.

या chapter साठी package system deeply शिकण्याची गरज नाही. सध्या एवढे लक्षात ठेवा:

Scanner वापरायचा असेल तर सामान्यतः import java.util.Scanner; आवश्यक आहे.

3. Scanner Object समजून घेऊ#

ही line पहा:

JAVA
Scanner scanner = new Scanner(System.in);

ती एकदम memorize करू नका.

तिचा basic अर्थ समजा.

Scanner#

Object चा type.

scanner#

आपण object ला दिलेले variable name.

हे नाव काहीही technically valid असू शकते:

JAVA
Scanner input = new Scanner(System.in);

किंवा:

JAVA
Scanner sc = new Scanner(System.in);

पण readable code साठी:

JAVA
scanner

हे चांगले descriptive नाव आहे.

new Scanner(...)#

नवीन Scanner object create करतो.

System.in#

Standard input source दर्शवतो.

आपल्या console program मध्ये सामान्यतः हा input keyboard वरून येतो.


Simple Mental Model#

TEXT
Keyboard
   ↓
System.in
   ↓
Scanner
   ↓
nextInt() / nextDouble() / next() / nextLine()
   ↓
Java Variable

उदाहरण:

JAVA
int age = scanner.nextInt();

Flow:

TEXT
User types 25
      ↓
Scanner reads 25
      ↓
nextInt() interprets it as int
      ↓
age = 25

4. Scanner Input Methods#

आपण या chapter मध्ये मुख्य methods वापरणार आहोत:

RequirementScanner Method
IntegernextInt()
DecimalnextDouble()
Single wordnext()
Complete linenextLine()
Characterdirect Scanner method नाही
First character of next tokennext().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#

JAVA
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#

TEXT
Enter your age: 25
Your age is 25

Important Line#

JAVA
int age = scanner.nextInt();

येथे दोन operations होत आहेत:

TEXT
scanner.nextInt()
        ↓
user कडून integer read
        ↓
returned int value
        ↓
age variable मध्ये store

Real Example: Product Quantity#

Suppose billing application मध्ये customer किती items घेणार आहे हे विचारायचे आहे.

JAVA
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#

TEXT
Enter product quantity: 4
Selected quantity: 4

6. nextInt() ला काय input अपेक्षित आहे?#

जर program लिहिला:

JAVA
int age = scanner.nextInt();

आणि user ने input दिले:

TEXT
30

तर योग्य.

पण user ने दिले:

TEXT
thirty

तर Scanner त्या token ला valid int म्हणून interpret करू शकत नाही.

त्यामुळे:

TEXT
InputMismatchException

येऊ शकते.

InputMismatchException indicates that the input token does not match the type expected by the Scanner method.

म्हणजे Scanner ज्या प्रकारची value अपेक्षित करत आहे, input त्या format मध्ये नाही.

उदा.:

TEXT
nextInt() expects integer
User enters: hello

Result:

TEXT
InputMismatchException

nextInt() ला पुढचा 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#

JAVA
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#

TEXT
Enter product price: 1499.50
Product price: 1499.5

तुम्ही input:

TEXT
1499.50

दिलात तरी double value print करताना:

TEXT
1499.5

दिसू शकते.

कारण numeric value म्हणून trailing zero display करण्याची आवश्यकता नसते.


Example: Temperature#

JAVA
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#

TEXT
Enter temperature: 36.7
Recorded temperature: 36.7

Integer आणि Decimal फरक#

JAVA
int quantity = scanner.nextInt();
double price = scanner.nextDouble();
InputAppropriate Type
5 itemsint
99.50 pricedouble
18 ageint
72.4 weightdouble

Data type requirement वरून method निवडा.

Method फक्त "number" पाहून निवडू नका.


Good to Know: Decimal Format and Locale#

Scanner numeric parsing locale-sensitive असू शकते.

Beginner examples मध्ये आपण:

TEXT
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 असतो:

JAVA
next()

आणि

JAVA
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 करतो.

उदाहरण:

TEXT
Rahul Patil

जर code:

JAVA
String name = scanner.next();

असेल तर result:

TEXT
Rahul

होऊ शकतो.

Patil हा पुढचा वेगळा token राहतो.


Example#

JAVA
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#

TEXT
Enter your first name: Rahul
Hello Rahul

Single-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#

JAVA
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#

TEXT
Enter your full name: Rahul Sanjay Patil
Welcome Rahul Sanjay Patil

11. next() vs nextLine()#

हा फरक खूप महत्त्वाचा आहे.

Featurenext()nextLine()
Return typeStringString
Readsnext tokenremaining complete line
Spaces inside textसाधारणपणे नाहीहो
Good forusername, city code, simple wordfull name, address, sentence

Example Input#

User types:

TEXT
Dattatray Sabne

Using next()#

JAVA
String name = scanner.next();

Result:

TEXT
Dattatray

Using nextLine()#

JAVA
String name = scanner.nextLine();

Result:

TEXT
Dattatray Sabne

Decision Rule#

Requirement:

Enter username

Possible input:

TEXT
dattatray

next() योग्य असू शकतो.

Requirement:

Enter full name

Possible input:

TEXT
Dattatray Sabne

nextLine() योग्य.

Requirement आधी समजा, method नंतर निवडा.


12. Reading Character#

Java beginner ला naturally वाटते:

JAVA
scanner.nextChar()

असे काहीतरी असावे.

पण Scanner मध्ये direct:

JAVA
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 असे समजू शकतो.

उदाहरण:

JAVA
char grade = 'A';

13. Scanner मधून Character कसा घ्यायचा?#

Common beginner pattern:

JAVA
char grade = scanner.next().charAt(0);

हे दोन steps मध्ये समजा.

Step 1#

JAVA
scanner.next()

String token read करतो.

जर user input:

TEXT
A

तर मिळते:

TEXT
"A"

Step 2#

JAVA
.charAt(0)

String मधील index 0 वरचा character घेतो.

Result:

TEXT
'A'

Full Example#

JAVA
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#

TEXT
Enter your grade: A
Your grade is A

Why index 0?#

String:

TEXT
Java

Indexes:

TEXT
J  a  v  a
0  1  2  3

म्हणून:

JAVA
"Java".charAt(0)

Result:

TEXT
J

जर user ने Male type केले तर?#

JAVA
char value = scanner.next().charAt(0);

Input:

TEXT
Male

Result:

TEXT
M

कारण आपण first token चा first character घेत आहोत.

यामुळे requirement clear असणे गरजेचे आहे.

जर requirement single character असेल:

TEXT
Enter section: A

user ला ते UI prompt मधून स्पष्ट करा.


14. Complete Example — Multiple Inputs#

आता integer, decimal, String आणि character एकत्र वापरू.

Requirement:

Student कडून घ्या:

  • full name
  • age
  • percentage
  • section

एक important problem येणार असल्यामुळे input order विचारपूर्वक ठेवू.

JAVA
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#

TEXT
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: A

15. Common Scanner Problem — nextInt() नंतर nextLine()#

हा Scanner चा सर्वात famous beginner problem आहे.

Code पहा:

JAVA
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:

TEXT
Enter age: 25

type करून Enter press करतो.

नंतर program full name input "skip" केल्यासारखा वाटू शकतो.


Problem का होतो?#

User types:

TEXT
25↵

Conceptually input मध्ये:

TEXT
25 + line separator

असतो.

nextInt():

JAVA
scanner.nextInt();

integer token:

TEXT
25

read करतो.

Scanner ची position integer नंतर असते.

नंतर:

JAVA
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 करा#

JAVA
int age = scanner.nextInt();
scanner.nextLine();

String name = scanner.nextLine();

पहिला:

JAVA
scanner.nextLine();

previous numeric input नंतर उरलेली line consume करतो.

दुसरा:

JAVA
scanner.nextLine();

actual full name read करतो.


Correct Example#

JAVA
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#

TEXT
Enter age: 25
Enter full name: Rahul Patil
Age: 25
Name: Rahul Patil

17. हा Problem फक्त nextInt() मुळेच आहे का?#

नाही.

General issue म्हणजे token-oriented methods आणि nextLine() mix करणे.

उदाहरणार्थ:

JAVA
nextInt()
nextDouble()
next()

हे token-oriented operations आहेत.

तर:

JAVA
nextLine()

line-oriented आहे.

विशेषतः numeric method नंतर लगेच nextLine() घेताना current line मध्ये काय उरले आहे ते विचार करा.


18. Better Mental Model: Token vs Line#

Input:

TEXT
25 Rahul Patil

Scanner कडे दोन वेगळ्या दृष्टीने पाहू शकतो.

Token View#

Default whitespace delimiter असल्यामुळे:

TEXT
Token 1 → 25
Token 2 → Rahul
Token 3 → Patil

Line View#

TEXT
Line 1 → 25 Rahul Patil

nextInt(), next(), nextDouble() सारखे methods token-based parsing करतात.

nextLine() line चा remaining भाग पाहतो.

हा फरक समजला की Scanner चे बरेच confusion आपोआप कमी होते.


19. Common Problem — Wrong Data Type#

Code:

JAVA
int age = scanner.nextInt();

Input:

TEXT
twenty five

Scanner ला हा token int मध्ये parse करता येत नाही.

Possible result:

TEXT
InputMismatchException

Mistake#

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:

TEXT
Enter your full name

Code:

JAVA
String name = scanner.next();

User:

TEXT
Rahul Sanjay Patil

Variable मध्ये:

TEXT
Rahul

इतकेच येते.

Root Cause#

next() पुढचा token read करतो.

Better Approach#

JAVA
String name = scanner.nextLine();

21. Common Problem — nextChar() वापरणे#

Wrong:

JAVA
char grade = scanner.nextChar();

Scanner मध्ये असा method उपलब्ध नाही.

Better#

JAVA
char grade = scanner.next().charAt(0);

22. Common Problem — चुकीचा charAt() index#

Code:

JAVA
char grade = scanner.next().charAt(1);

Input:

TEXT
A

String length फक्त 1 आहे.

Valid index:

TEXT
0

1 नाही.

Single-character token साठी:

JAVA
char grade = scanner.next().charAt(0);

वापरा.


23. Common Problem — अनेक Scanner Objects#

Beginner कधी कधी प्रत्येक input साठी नवीन object create करतो:

JAVA
Scanner scanner1 = new Scanner(System.in);
Scanner scanner2 = new Scanner(System.in);
Scanner scanner3 = new Scanner(System.in);

Basic console application साठी हे unnecessary आहे.

Prefer:

JAVA
Scanner scanner = new Scanner(System.in);

आणि तोच object reuse करा:

JAVA
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 आहे.

उदाहरण:

JAVA
scanner.close();

पण एक important practical point आहे:

JAVA
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#

DataTypeInput Method
Full nameStringnextLine()
AgeintnextInt()
CourseStringnext() or nextLine()
FeedoublenextDouble()
Batch codecharnext().charAt(0)

जर course नाव:

TEXT
Java

असेल तर next() पुरेसे असू शकते.

पण:

TEXT
Java Beginner Course

असेल तर nextLine() आवश्यक आहे.

Requirement method ठरवते.


Implementation#

JAVA
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#

TEXT
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: A

Professional Reasoning#

कोणता Scanner method वापरायचा हे syntax question नाही.

ते data requirement question आहे.

Developer ने विचारले पाहिजे:

TEXT
या 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#

आपल्याकडे:

TEXT
nextInt()
nextDouble()

आहेत.

म्हणून naturally:

TEXT
nextChar()

असेल असे वाटते.

Correct Understanding#

Scanner मध्ये direct nextChar() नाही.

Common beginner approach:

JAVA
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:

JAVA
scanner.nextInt();

Input:

TEXT
twenty

Scanner magically 20 बनवेल.

असे होत नाही.

Input expected format मध्ये असणे आवश्यक आहे.


Misconception 5: प्रत्येक input साठी नवीन Scanner हवा#

नाही.

सामान्य console program मध्ये एक Scanner object तयार करून reuse करणे cleaner आहे.


Misconception 6: nextDouble() म्हणजे फक्त decimal point असलेली value#

नाही.

Input:

TEXT
100

हे सुद्धा double म्हणून parse होऊ शकते आणि value:

TEXT
100.0

म्हणून represent होऊ शकते.

Method निवडताना input च्या business meaning कडे बघा.


27. Hands-On Practice#

Practice 1 — Employee Age#

Requirement#

User कडून employee age घ्या आणि print करा.

Learner Task#

Output pattern:

TEXT
Enter employee age: 30
Employee age: 30

Hint 1#

Age whole number आहे.

Hint 2#

Use:

JAVA
nextInt()

Solution#

JAVA
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#

TEXT
Enter price: 749.50
Price: 749.5

Hint#

Use a decimal-capable type.

Solution#

JAVA
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#

TEXT
Rahul Ashok Patil

Wrong Choice#

JAVA
scanner.next();

Hint#

Complete line हवी आहे.

Solution#

JAVA
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:

TEXT
A

Hint#

Scanner मध्ये direct nextChar() नाही.

Solution#

JAVA
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:

JAVA
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#

JAVA
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:

JAVA
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?
JAVA
Scanner scanner = new Scanner(System.in);

You normally import it using:

JAVA
import java.util.Scanner;

3. Which Scanner method is commonly used to read an integer?

nextInt().

Example:

JAVA
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:

JAVA
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:

TEXT
Rahul Patil

next() normally returns:

TEXT
Rahul

while nextLine() can return:

TEXT
Rahul Patil

Common 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:

JAVA
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:

JAVA
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:

JAVA
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:

TEXT
Expected: 25
Entered: twenty-five

10. 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:

TEXT
Java Beginner Course

is normally seen as three tokens:

TEXT
Java
Beginner
Course

14. 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:

TEXT
100.0

29. Quick Revision#

Create Scanner#

JAVA
Scanner scanner = new Scanner(System.in);

Import:

JAVA
import java.util.Scanner;

Integer#

JAVA
int age = scanner.nextInt();

Decimal#

JAVA
double price = scanner.nextDouble();

Single Token#

JAVA
String username = scanner.next();

Complete Line#

JAVA
String fullName = scanner.nextLine();

Character#

JAVA
char grade = scanner.next().charAt(0);

Important Difference#

TEXT
next()     → next token
nextLine() → remaining current line

Famous Scanner Problem#

Problem:

JAVA
int age = scanner.nextInt();
String name = scanner.nextLine();

Better:

JAVA
int age = scanner.nextInt();
scanner.nextLine();
String name = scanner.nextLine();

Invalid Integer Input#

JAVA
scanner.nextInt();

आणि input:

TEXT
hello

असल्यास:

TEXT
InputMismatchException

येऊ शकते.


30. You Should Now Be Able To#

तुम्हाला आता independently:

  • Scanner म्हणजे काय हे explain करता आले पाहिजे.
  • Scanner console 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 कडून घ्यायचे आहे:

TEXT
Employee ID
Full Name
Salary
Department Name
Performance Grade

Data Requirements#

TEXT
Employee ID        → whole number
Full Name          → spaces allowed
Salary             → decimal allowed
Department Name    → spaces allowed
Performance Grade  → one character

Learner Task#

योग्य:

  • Java data types
  • Scanner methods
  • input order
  • nextLine() handling

निवडून complete program तयार करा.


Hints#

Hint 1#

Employee ID:

JAVA
nextInt()

Hint 2#

ID read केल्यानंतर full name घ्यायचे आहे.

Token-to-line transition लक्षात ठेवा.

Hint 3#

Salary:

JAVA
nextDouble()

Hint 4#

Salary नंतर department चे full text घ्यायचे असल्यामुळे पुन्हा line transition विचारात घ्या.

Hint 5#

Grade:

JAVA
next().charAt(0)

Solution#

JAVA
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#

TEXT
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: A

Reasoning#

Employee ID साठी:

JAVA
nextInt()

Salary साठी:

JAVA
nextDouble()

Full name आणि department मध्ये spaces येऊ शकतात म्हणून:

JAVA
nextLine()

Performance grade single character असल्यामुळे:

JAVA
next().charAt(0)

आणि numeric input वरून nextLine() कडे transition होताना pending line consume करण्यासाठी:

JAVA
scanner.nextLine();

वापरले आहे.