Lesson:
Input
Cracking the Coding Interview in JAVA - Foundation
Pre-Requisites:
List of Concepts Involved:
Java Basic syntax
Variables
Data types
Taking input from user


Before getting into the actual input programs, lets first look into the brief description of the commonly used
jargons.



Class : a class is a template definition of the methods and variables in a particular kind of object. 



Object: Object is an instance of a class. It is actually a real world entity. 

Lets see the example below for better understanding.
Here, you can see that class ‘Car’ is just a blueprint. However, the objects actually are the real world entities
which have their own features.



Package: A package in Java is used to group related classes. Think of it as a folder in a file directory. We use
packages to avoid name conflicts, and to write a better maintainable code.


Let us begin !
Cracking the Coding Interview in JAVA - Foundation
Topic: How to get input from users in Java?
The easiest way to read input (primitive) in a Java program is through scanner class. 


Java Scanner Class

Java Scanner class allows the user to take input from the console. It belongs to the java.util package. It is used
to read the input of primitive types like int, double, long, short, float, and byte. 


The Java Scanner class then breaks the input into tokens using a delimiter (whitespace by default). It provides
many ways to read and parse various primitive values. 


In order to use scanner you have to write this import statement at the top – 

import java.util.Scanner; 



Example code for taking integer input in java

import java.util.Scanner; 

public class Main{

public static void main(String[] args){

int num;

System.out.println(“Enter a number”);

Scanner sc = new Scanner(System.in); 

num=sc.nextInt(); 

System.out.println(num);

num=num+5;

System.out.println(num);

}

}


Example code:



import java.util.Scanner;

class AddNumbers { 

public static void main(String args[]) { 

int num1,num2,sum;

System.out.println("Enter two numbers to calculate their sum: ");



Scanner sc = new Scanner(System.in); 

num1=sc.nextInt(); 

num2 = sc.nextInt(); 

sum= num1 + num2; 

System.out.println(sum); 

} 

}


Sample Input: 10 5 

Output: 15

Here, sc.nextInt() scans and returns the next token as int. A token is part of an entered line that is separated
from other tokens by space, tab or newline. So when input line is: “10 5” then sc.nextInt() returns the first token
i.e. “10” as int and sc.nextInt() again returns the next token i.e. “5” as int.
//Code for adding two integers entered by the user
// Create a Scanner
Cracking the Coding Interview in JAVA - Foundation
Example code for calculation of simple interest: 

import java.util.Scanner;

class Main { 

public static void main(String[] args) { 

Scanner sc = new Scanner(System.in);



System.out.print("Enter the principal amount: ");

double principal = sc.nextDouble();

System.out.print("Enter the interest rate: ");

double rate = sc.nextDouble();

System.out.print("Enter the time: ");

double time = sc.nextDouble();

double interest = (principal * time * rate) / 100;

System.out.println("Principal: " + principal);

System.out.println("Interest Rate: " + rate);

System.out.println("Time Duration: " + time);

System.out.println("Simple Interest: " + interest);

}

}


Output:

Enter the principal: 500

Enter the rate : 8

Enter the time: 2

Principal :500.00

Interest Rate: 8.0

Time Duration: 2.0

Simple Interest : 80.0




import java.util.Scanner;

public class Main

{ 

public static void main(String[] args)

{


Scanner sc = new Scanner(System.in);



char ch = sc.next().charAt(0);



System.out.println("char = "+ch);

}

}


Input :

h

Output :

char = h
// create an object of Scanner class

// take input from users
// Java program to read character using Scanner class
// Declare the object and initialize with

// predefined standard input object
// Character input
// Print the read value
Cracking the Coding Interview in JAVA - Foundation
Java Scanner Methods to Take Input

The Scanner class provides various methods that allow us to read inputs of different types. Lets see a few of
them in the table below :
Try and explore all of these scanner methods in the same way as we did in the previous examples. This will
make you an expert with scanner method applications.
Cracking the Coding Interview in JAVA - Foundation
MCQs
Upcoming Class Teasers
1.What is the output of the following code if input is :

20 physics wallah



Scanner s = new Scanner(System.in);

int p = s.nextInt();

String q = s.next();

System.out.print(p);

System.out.println(q);


Options
20 physics wallah
20physics
20physicswallah
20 physics 


Ans: b) 20physics

Explanation:

"s.nextInt()" scans and returns the next token as int. A token is part of an entered line that is separated from
other tokens by space, tab or newline. So when input line is - “20 physics wallah” then s.nextInt() returns the first
token as int i.e. “20” and s.next() returns the next token "physics”. 

While printing, in the first statement p is printed and then q. There is no space or nextline between both prints.
Hence output is : 20physics.



2.What is the output of the following code if input is : hello world 21


Scanner sc = new Scanner(System.in);

String p = sc.next();

int q=sc.nextInt();

System.out.print(p + " " + q);


Options:
hello world 21
InputMismatchException
hello 21
hello


Ans b) InputMismatchException

Explanation:

"sc.next()" scans and returns the next token as String. A token is part of an entered line that is separated from
other tokens by space, tab or newline. So when input line is - “ hello world 21” then sc.next() returns the first
token as String i.e. “hello” and sc.nextInt() tries to convert the next token i.e. “world” into an int, which gives
InputMismatchException.
Operators
Precedence and their associativity

More Related Content

PPTX
Computer programming 2 chapter 1-lesson 2
PDF
Lecture 2 java.pdf
DOCX
Java Practical1 based on Basic assignment
PPTX
Lab01.pptx
PPT
07-Basic-Input-Output.ppt
DOCX
Java file
DOCX
Java file
DOCX
How to get input from usjer in Java.docx
Computer programming 2 chapter 1-lesson 2
Lecture 2 java.pdf
Java Practical1 based on Basic assignment
Lab01.pptx
07-Basic-Input-Output.ppt
Java file
Java file
How to get input from usjer in Java.docx

Similar to 3.Lesson Plan - Input.pdf.pdf (20)

PDF
Java Practical File Diploma
PDF
Problem1 java codeimport java.util.Scanner; Java code to pr.pdf
PPTX
Lab101.pptx
DOCX
LAB1.docx
PPT
Introduction to Java Programming Part 2
PDF
import java.util.;public class Program{public static void.pdf
PDF
Object Oriented Solved Practice Programs C++ Exams
PPTX
Lecture-5Programming WorldJava Lecture.pptx
DOCX
PDF
Simple Java Program for beginner with easy method.pdf
PDF
Core java pract_sem iii
PPTX
KOLEJ KOMUNITI - Sijil Aplikasi Perisian Komputer
PDF
Simple 27 Java Program on basic java syntax
PDF
Java programming lab manual
ODT
Java practical
PPT
09-ch04-1-scanner class in java with explainiation
PPT
ppt on scanner class
DOC
Java final lab
PDF
MagicSquareTest.java import java.util.Scanner;public class Mag.pdf
PPTX
JAVA Question : Programming Assignment
Java Practical File Diploma
Problem1 java codeimport java.util.Scanner; Java code to pr.pdf
Lab101.pptx
LAB1.docx
Introduction to Java Programming Part 2
import java.util.;public class Program{public static void.pdf
Object Oriented Solved Practice Programs C++ Exams
Lecture-5Programming WorldJava Lecture.pptx
Simple Java Program for beginner with easy method.pdf
Core java pract_sem iii
KOLEJ KOMUNITI - Sijil Aplikasi Perisian Komputer
Simple 27 Java Program on basic java syntax
Java programming lab manual
Java practical
09-ch04-1-scanner class in java with explainiation
ppt on scanner class
Java final lab
MagicSquareTest.java import java.util.Scanner;public class Mag.pdf
JAVA Question : Programming Assignment
Ad

Recently uploaded (20)

PPTX
Core Concepts of Personalized Learning and Virtual Learning Environments
PDF
International_Financial_Reporting_Standa.pdf
PDF
HVAC Specification 2024 according to central public works department
PDF
LIFE & LIVING TRILOGY- PART (1) WHO ARE WE.pdf
DOCX
Cambridge-Practice-Tests-for-IELTS-12.docx
PPTX
Introduction to pro and eukaryotes and differences.pptx
PPTX
What’s under the hood: Parsing standardized learning content for AI
PDF
Uderstanding digital marketing and marketing stratergie for engaging the digi...
PDF
BP 704 T. NOVEL DRUG DELIVERY SYSTEMS (UNIT 1)
PPTX
ELIAS-SEZIURE AND EPilepsy semmioan session.pptx
PDF
Τίμαιος είναι φιλοσοφικός διάλογος του Πλάτωνα
PPTX
Unit 4 Computer Architecture Multicore Processor.pptx
PDF
BP 704 T. NOVEL DRUG DELIVERY SYSTEMS (UNIT 2).pdf
PPTX
Computer Architecture Input Output Memory.pptx
PDF
Journal of Dental Science - UDMY (2021).pdf
PDF
BP 505 T. PHARMACEUTICAL JURISPRUDENCE (UNIT 1).pdf
PDF
AI-driven educational solutions for real-life interventions in the Philippine...
PDF
My India Quiz Book_20210205121199924.pdf
PDF
MICROENCAPSULATION_NDDS_BPHARMACY__SEM VII_PCI .pdf
PDF
Complications of Minimal Access-Surgery.pdf
Core Concepts of Personalized Learning and Virtual Learning Environments
International_Financial_Reporting_Standa.pdf
HVAC Specification 2024 according to central public works department
LIFE & LIVING TRILOGY- PART (1) WHO ARE WE.pdf
Cambridge-Practice-Tests-for-IELTS-12.docx
Introduction to pro and eukaryotes and differences.pptx
What’s under the hood: Parsing standardized learning content for AI
Uderstanding digital marketing and marketing stratergie for engaging the digi...
BP 704 T. NOVEL DRUG DELIVERY SYSTEMS (UNIT 1)
ELIAS-SEZIURE AND EPilepsy semmioan session.pptx
Τίμαιος είναι φιλοσοφικός διάλογος του Πλάτωνα
Unit 4 Computer Architecture Multicore Processor.pptx
BP 704 T. NOVEL DRUG DELIVERY SYSTEMS (UNIT 2).pdf
Computer Architecture Input Output Memory.pptx
Journal of Dental Science - UDMY (2021).pdf
BP 505 T. PHARMACEUTICAL JURISPRUDENCE (UNIT 1).pdf
AI-driven educational solutions for real-life interventions in the Philippine...
My India Quiz Book_20210205121199924.pdf
MICROENCAPSULATION_NDDS_BPHARMACY__SEM VII_PCI .pdf
Complications of Minimal Access-Surgery.pdf
Ad

3.Lesson Plan - Input.pdf.pdf

  • 2. Cracking the Coding Interview in JAVA - Foundation Pre-Requisites: List of Concepts Involved: Java Basic syntax Variables Data types Taking input from user Before getting into the actual input programs, lets first look into the brief description of the commonly used jargons. Class : a class is a template definition of the methods and variables in a particular kind of object. Object: Object is an instance of a class. It is actually a real world entity. Lets see the example below for better understanding. Here, you can see that class ‘Car’ is just a blueprint. However, the objects actually are the real world entities which have their own features. Package: A package in Java is used to group related classes. Think of it as a folder in a file directory. We use packages to avoid name conflicts, and to write a better maintainable code. Let us begin !
  • 3. Cracking the Coding Interview in JAVA - Foundation Topic: How to get input from users in Java? The easiest way to read input (primitive) in a Java program is through scanner class. Java Scanner Class Java Scanner class allows the user to take input from the console. It belongs to the java.util package. It is used to read the input of primitive types like int, double, long, short, float, and byte. The Java Scanner class then breaks the input into tokens using a delimiter (whitespace by default). It provides many ways to read and parse various primitive values. In order to use scanner you have to write this import statement at the top – import java.util.Scanner; Example code for taking integer input in java import java.util.Scanner; public class Main{ public static void main(String[] args){ int num; System.out.println(“Enter a number”); Scanner sc = new Scanner(System.in); num=sc.nextInt(); System.out.println(num); num=num+5; System.out.println(num); } } Example code: import java.util.Scanner; class AddNumbers { public static void main(String args[]) { int num1,num2,sum; System.out.println("Enter two numbers to calculate their sum: "); Scanner sc = new Scanner(System.in); num1=sc.nextInt(); num2 = sc.nextInt(); sum= num1 + num2; System.out.println(sum); } } Sample Input: 10 5 Output: 15 Here, sc.nextInt() scans and returns the next token as int. A token is part of an entered line that is separated from other tokens by space, tab or newline. So when input line is: “10 5” then sc.nextInt() returns the first token i.e. “10” as int and sc.nextInt() again returns the next token i.e. “5” as int. //Code for adding two integers entered by the user // Create a Scanner
  • 4. Cracking the Coding Interview in JAVA - Foundation Example code for calculation of simple interest: import java.util.Scanner; class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter the principal amount: "); double principal = sc.nextDouble(); System.out.print("Enter the interest rate: "); double rate = sc.nextDouble(); System.out.print("Enter the time: "); double time = sc.nextDouble(); double interest = (principal * time * rate) / 100; System.out.println("Principal: " + principal); System.out.println("Interest Rate: " + rate); System.out.println("Time Duration: " + time); System.out.println("Simple Interest: " + interest); } } Output: Enter the principal: 500 Enter the rate : 8 Enter the time: 2 Principal :500.00 Interest Rate: 8.0 Time Duration: 2.0 Simple Interest : 80.0 import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); char ch = sc.next().charAt(0); System.out.println("char = "+ch); } } Input : h Output : char = h // create an object of Scanner class // take input from users // Java program to read character using Scanner class // Declare the object and initialize with // predefined standard input object // Character input // Print the read value
  • 5. Cracking the Coding Interview in JAVA - Foundation Java Scanner Methods to Take Input The Scanner class provides various methods that allow us to read inputs of different types. Lets see a few of them in the table below : Try and explore all of these scanner methods in the same way as we did in the previous examples. This will make you an expert with scanner method applications.
  • 6. Cracking the Coding Interview in JAVA - Foundation MCQs Upcoming Class Teasers 1.What is the output of the following code if input is : 20 physics wallah Scanner s = new Scanner(System.in); int p = s.nextInt(); String q = s.next(); System.out.print(p); System.out.println(q); Options 20 physics wallah 20physics 20physicswallah 20 physics Ans: b) 20physics Explanation: "s.nextInt()" scans and returns the next token as int. A token is part of an entered line that is separated from other tokens by space, tab or newline. So when input line is - “20 physics wallah” then s.nextInt() returns the first token as int i.e. “20” and s.next() returns the next token "physics”. While printing, in the first statement p is printed and then q. There is no space or nextline between both prints. Hence output is : 20physics. 2.What is the output of the following code if input is : hello world 21 Scanner sc = new Scanner(System.in); String p = sc.next(); int q=sc.nextInt(); System.out.print(p + " " + q); Options: hello world 21 InputMismatchException hello 21 hello Ans b) InputMismatchException Explanation: "sc.next()" scans and returns the next token as String. A token is part of an entered line that is separated from other tokens by space, tab or newline. So when input line is - “ hello world 21” then sc.next() returns the first token as String i.e. “hello” and sc.nextInt() tries to convert the next token i.e. “world” into an int, which gives InputMismatchException. Operators Precedence and their associativity