SlideShare a Scribd company logo
University of Kufa
Collage of Computer Science
and Mathematics
Lecture 3
‫م‬
.
‫االمين‬ ‫الحسن‬ ‫عبد‬ ‫هدى‬ ‫م‬
 The Scanner class is used to get user input, and it is found in the java.util package.
 To use the Scanner class, create an object of the class and use any of the available methods
found in the Scanner class documentation. In our examples, we will use the nextLine() method,
which is used to read Strings:
Java User Input (Scanner)
the nextInt () method, which is used to read int
the nextLine () method, which is used to read string
Java User Input (Scanner)
import java.util.Scanner; // Import the Scanner class
class MyClass {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter username");
String userName = myObj.nextLine(); // Read user input
System.out.println("Username is: " + userName); // Output user input } }
Java User Input (Scanner)
import java.util.Scanner; // Import the Scanner class
class MyClass {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter username");
String userName = myObj.nextLine(); // Read user input
System.out.println("Username is: " + userName); // Output user input } }
Java User Input (Scanner)
Java User Input (Scanner)
 Some programming statements allow us to make decisions and perform
repetitions
 These decisions are based on boolean expressions (also called conditions) that
evaluate to true or false
 The order of statement execution is called the flow of control
Flow of Control
 A conditional statement lets us choose which statement will be executed next
 They are sometimes called selection statements
 Conditional statements give us the power to make basic decisions
 The Java conditional statements are the:
 if and if-else statement
 switch statement
Flow of Control
The if Statement
 Let's now look at the if statement in more detail
 The if statement has the following syntax:
if ( condition )
statement;
if is a Java
reserved word
The condition must be a
boolean expression. It must
evaluate to either true or false.
If the condition is true, the statement is executed.
If it is false, the statement is skipped.
Logic of an if statement
condition
evaluated
false
statement
true
 A condition often uses one of Java's equality operators or relational operators,
which all return boolean results:
==equal to
!=not equal to
< less than
> greater than
<=less than or equal to
>=greater than or equal to
 Note the difference between the equality operator (==) and the assignment
operator (=)
Boolean Expressions
 An if statement with its boolean condition:
if (sum > MAX)
delta = sum – MAX;
 First, the condition is evaluated: the value of sum is either greater than the
value of MAX, or it is not
 If the condition is true, the assignment statement is executed; if it isn't, it is
skipped
Boolean Expressions
//********************************************************************
// Age.java Author: Lewis/Loftus
//
// Demonstrates the use of an if statement.
//********************************************************************
import java.util.Scanner;
public class Age
{
//-----------------------------------------------------------------
// Reads the user's age and prints comments accordingly.
//-----------------------------------------------------------------
public static void main (String[] args)
{
final int MINOR = 21;
Scanner scan = new Scanner (System.in);
System.out.print ("Enter your age: ");
int age = scan.nextInt();
continue
continue
System.out.println ("You entered: " + age);
if (age < MINOR)
System.out.println ("Youth is a wonderful thing. Enjoy.");
System.out.println ("Age is a state of mind.");
}
}
continue
System.out.println ("You entered: " + age);
if (age < MINOR)
System.out.println ("Youth is a wonderful thing. Enjoy.");
System.out.println ("Age is a state of mind.");
}
}
Sample Run
Enter your age: 47
You entered: 47
Age is a state of mind.
Another Sample Run
Enter your age: 12
You entered: 12
Youth is a wonderful thing. Enjoy.
Age is a state of mind.
Logical Operators
 Boolean expressions can also use the following logical operators:
! Logical NOT
&& Logical AND
|| Logical OR
 They all take boolean operands and produce boolean results
 Logical NOT is a unary operator (it operates on one operand)
 Logical AND and logical OR are binary operators (each operates on two
operands)
Logical NOT
 The logical NOT operation is also called logical negation or logical complement
 If some boolean condition a is true, then !a is false; if a is false, then !a is
true
 Logical expressions can be shown using a truth table:
a !a
true false
false true
Logical AND and Logical OR
 The logical AND expression
a && b
is true if both a and b are true, and false otherwise
 The logical OR expression
a || b
is true if a or b or both are true, and false otherwise
Logical AND and Logical OR
 A truth table shows all possible true-false combinations of the terms
 Since && and || each have two operands, there are four possible combinations
of conditions a and b
a b a && b a || b
true true True true
true false false true
false true false true
false false false false
Logical Operators
 Expressions that use logical operators can form complex conditions
if (total < MAX+5 && !found)
System.out.println ("Processing…");
 All logical operators have lower precedence than the relational operators
 The ! operator has higher precedence than && and ||
The if-else Statement
 An else clause can be added to an if statement to make an if-else statement
if ( condition )
statement1;
else
statement2;
 If the condition is true, statement1 is executed; if the condition is false,
statement2 is executed
 One or the other will be executed, but not both
Java input Scanner
Logic of an if-else statement
condition
evaluated
false
statement2
statement
true
Nested if Statements
 The statement executed as a result of an if or else clause could be another
if statement
 These are called nested if statements
 An else clause is matched to the last unmatched if (no matter what the
indentation implies)
 Braces can be used to specify the if statement to which an else clause
belongs
 See MinOfThree.java
Java input Scanner
Java input Scanner
Java input Scanner
Switch Case statement
 Switch case statement is used when we have number of options (or choices)
and we may need to perform a different task for each choice.
 The syntax of Switch case statement looks like this
Switch Case statement: Example
Switch Case statement: Example
Switch Case Flow Diagram
 First the variable, value or expression which is provided in the switch
parenthesis is evaluated and then based on the result, the corresponding case
block is executed that matches the result.
Java input Scanner
Break statement in Switch Case
 Break statement is optional in switch case but you would use it almost every
time you deal with switch case. Before we discuss about break statement,
Let’s have a look at the example below where I am not using the break
statement:
Break statement in Switch Case: Example
Break statement in Switch Case: Example
Break statement in Switch Case: Example
In the above program, we have passed integer value 2 to the switch, so the control
switched to the case 2
,
revewoh
ew
nod
’ t have break statement after the case 2 that
caused the flow to pass to the subsequent cases till the end .
The solution to this problem is break statement
Break statements are used when you want your program-flow to come out of the switch
body. Whenever a break statement is encountered in the switch body, the execution
flow would directly come out of the switch, ignoring rest of the cases Let’s take the
same example but this time with break statement.
Java input Scanner
Java input Scanner

More Related Content

What's hot (20)

DOCX
Java loops
ricardovigan
 
PPTX
Loops Basics
Mushiii
 
PPT
Looping in c++
deekshagopaliya
 
PPTX
Loops in C Programming Language
Mahantesh Devoor
 
PPTX
Control statements in java
Madishetty Prathibha
 
PPTX
Loops in c language
tanmaymodi4
 
PPTX
Loop(for, while, do while) condition Presentation
Badrul Alam
 
PPTX
While , For , Do-While Loop
Abhishek Choksi
 
PPTX
Loops in C
Kamal Acharya
 
PPT
Java Programming: Loops
Karwan Mustafa Kareem
 
PDF
While loops
Michael Gordon
 
PDF
Control statements anil
Anil Dutt
 
PDF
Chapter 9 - Loops in C++
Deepak Singh
 
PPTX
Java loops for, while and do...while
Jayfee Ramos
 
PDF
Chapter 3
Amrit Kaur
 
PPT
M C6java6
mbruggen
 
PPTX
Do...while loop structure
Jd Mercado
 
Java loops
ricardovigan
 
Loops Basics
Mushiii
 
Looping in c++
deekshagopaliya
 
Loops in C Programming Language
Mahantesh Devoor
 
Control statements in java
Madishetty Prathibha
 
Loops in c language
tanmaymodi4
 
Loop(for, while, do while) condition Presentation
Badrul Alam
 
While , For , Do-While Loop
Abhishek Choksi
 
Loops in C
Kamal Acharya
 
Java Programming: Loops
Karwan Mustafa Kareem
 
While loops
Michael Gordon
 
Control statements anil
Anil Dutt
 
Chapter 9 - Loops in C++
Deepak Singh
 
Java loops for, while and do...while
Jayfee Ramos
 
Chapter 3
Amrit Kaur
 
M C6java6
mbruggen
 
Do...while loop structure
Jd Mercado
 

Similar to Java input Scanner (20)

PPTX
ICSE Class X Conditional Statements in java
VanitaKarthik2
 
PPTX
130706266060138191
Tanzeel Ahmad
 
PPT
slides03.ppt
Anjali127411
 
PPTX
3. Java Installations ppt for engineering
vyshukodumuri
 
PPTX
Java Chapter 05 - Conditions & Loops: part 2
DanWooster1
 
PDF
Week03
hccit
 
PPTX
Java basics and java variables
Pushpendra Tyagi
 
PPT
Switch and control statement for c language
BalaKrishnan466
 
PPT
Switch and control looping statement for C
BalaKrishnan466
 
PPT
Switch and looping statement for c language
BalaKrishnan466
 
PDF
9-java language basics part3
Amr Elghadban (AmrAngry)
 
PPTX
Flow of control by deepak lakhlan
Deepak Lakhlan
 
PPT
java switch
MuhammadShahidShamoo
 
PPTX
Java chapter 3
Abdii Rashid
 
PPTX
Control structures
Gehad Enayat
 
PPTX
control statements
Azeem Sultan
 
PPT
Control statements
CutyChhaya
 
PPT
Java Programmin: Selections
Karwan Mustafa Kareem
 
PPT
Control structure and Looping statements
BalaKrishnan466
 
PPTX
Conditional Statement
OXUS 20
 
ICSE Class X Conditional Statements in java
VanitaKarthik2
 
130706266060138191
Tanzeel Ahmad
 
slides03.ppt
Anjali127411
 
3. Java Installations ppt for engineering
vyshukodumuri
 
Java Chapter 05 - Conditions & Loops: part 2
DanWooster1
 
Week03
hccit
 
Java basics and java variables
Pushpendra Tyagi
 
Switch and control statement for c language
BalaKrishnan466
 
Switch and control looping statement for C
BalaKrishnan466
 
Switch and looping statement for c language
BalaKrishnan466
 
9-java language basics part3
Amr Elghadban (AmrAngry)
 
Flow of control by deepak lakhlan
Deepak Lakhlan
 
Java chapter 3
Abdii Rashid
 
Control structures
Gehad Enayat
 
control statements
Azeem Sultan
 
Control statements
CutyChhaya
 
Java Programmin: Selections
Karwan Mustafa Kareem
 
Control structure and Looping statements
BalaKrishnan466
 
Conditional Statement
OXUS 20
 
Ad

More from Huda Alameen (19)

PDF
Architectural design
Huda Alameen
 
PDF
System Modeling
Huda Alameen
 
PDF
Requirements Engineering
Huda Alameen
 
PDF
Java Print method
Huda Alameen
 
PDF
Softweare Engieering
Huda Alameen
 
PDF
Softweare Engieering
Huda Alameen
 
PDF
Structured query language(sql)
Huda Alameen
 
PDF
Sql viwes
Huda Alameen
 
PDF
Relational algebra
Huda Alameen
 
PDF
Normalization
Huda Alameen
 
PDF
Lecture one db
Huda Alameen
 
PDF
Introduction to structured query language
Huda Alameen
 
PDF
Indexing techniques
Huda Alameen
 
PDF
Agg fun
Huda Alameen
 
PDF
Se lec1 (1)
Huda Alameen
 
PDF
Se lec6
Huda Alameen
 
PDF
Se lec5
Huda Alameen
 
PDF
Se lec 4
Huda Alameen
 
PDF
Se lec 3
Huda Alameen
 
Architectural design
Huda Alameen
 
System Modeling
Huda Alameen
 
Requirements Engineering
Huda Alameen
 
Java Print method
Huda Alameen
 
Softweare Engieering
Huda Alameen
 
Softweare Engieering
Huda Alameen
 
Structured query language(sql)
Huda Alameen
 
Sql viwes
Huda Alameen
 
Relational algebra
Huda Alameen
 
Normalization
Huda Alameen
 
Lecture one db
Huda Alameen
 
Introduction to structured query language
Huda Alameen
 
Indexing techniques
Huda Alameen
 
Agg fun
Huda Alameen
 
Se lec1 (1)
Huda Alameen
 
Se lec6
Huda Alameen
 
Se lec5
Huda Alameen
 
Se lec 4
Huda Alameen
 
Se lec 3
Huda Alameen
 
Ad

Recently uploaded (20)

PPTX
SCIENCE 4 Q1- WEEK 2 DAY 1 Matatag Grade 4
AngieLeaSerraYlarde
 
PDF
The ALMA-CRISTAL survey: Gas, dust, and stars in star-forming galaxies when t...
Sérgio Sacani
 
PDF
BlackBody Radiation experiment report.pdf
Ghadeer Shaabna
 
PPTX
SCHOOL HOLIDAY REVISION CHAPTER 8.pptx science kssm
SITIATHIRAHBINTISULA
 
PPTX
CLIMATE CHANGE BY SIR AHSAN HISTORY.pptx
GulFeroze
 
PPTX
Renewable Energy Resources - Introduction
BhajneetSingh1
 
PDF
The scientific heritage No 163 (163) (2025)
The scientific heritage
 
PDF
Lab 3 the microscope uses for students.pdf
jamie088j
 
PDF
thesis dr Zahida and samia on plasma physics.pdf
HamzaKhalid267437
 
PPT
Supercapacitor materials For Material science
AnasBalghaith1
 
PDF
Carbonate formation and fluctuating habitability on Mars
Sérgio Sacani
 
PDF
Preserving brand authenticity amid AI-driven misinformation: Sustaining consu...
Selcen Ozturkcan
 
PDF
Voyage to the Cosmos of Consciousness.pdf
Saikat Basu
 
PDF
Rational points on curves -- BIMR 2025 --
mmasdeu
 
PDF
2025 Insilicogen Company Korean Brochure
Insilico Gen
 
PDF
Calcium in a supernova remnant as a fingerprint of a sub-Chandrasekhar-mass e...
Sérgio Sacani
 
DOCX
Critical Book Review (CBR) - "Hate Speech: Linguistic Perspectives"
Sahmiral Amri Rajagukguk
 
PDF
20250603 Recycling 4.pdf . Rice flour, aluminium, hydrogen, paper, cardboard.
Sharon Liu
 
PDF
Webinar: World's Smallest Pacemaker
Scintica Instrumentation
 
PDF
2025 Insilicogen Company English Brochure
Insilico Gen
 
SCIENCE 4 Q1- WEEK 2 DAY 1 Matatag Grade 4
AngieLeaSerraYlarde
 
The ALMA-CRISTAL survey: Gas, dust, and stars in star-forming galaxies when t...
Sérgio Sacani
 
BlackBody Radiation experiment report.pdf
Ghadeer Shaabna
 
SCHOOL HOLIDAY REVISION CHAPTER 8.pptx science kssm
SITIATHIRAHBINTISULA
 
CLIMATE CHANGE BY SIR AHSAN HISTORY.pptx
GulFeroze
 
Renewable Energy Resources - Introduction
BhajneetSingh1
 
The scientific heritage No 163 (163) (2025)
The scientific heritage
 
Lab 3 the microscope uses for students.pdf
jamie088j
 
thesis dr Zahida and samia on plasma physics.pdf
HamzaKhalid267437
 
Supercapacitor materials For Material science
AnasBalghaith1
 
Carbonate formation and fluctuating habitability on Mars
Sérgio Sacani
 
Preserving brand authenticity amid AI-driven misinformation: Sustaining consu...
Selcen Ozturkcan
 
Voyage to the Cosmos of Consciousness.pdf
Saikat Basu
 
Rational points on curves -- BIMR 2025 --
mmasdeu
 
2025 Insilicogen Company Korean Brochure
Insilico Gen
 
Calcium in a supernova remnant as a fingerprint of a sub-Chandrasekhar-mass e...
Sérgio Sacani
 
Critical Book Review (CBR) - "Hate Speech: Linguistic Perspectives"
Sahmiral Amri Rajagukguk
 
20250603 Recycling 4.pdf . Rice flour, aluminium, hydrogen, paper, cardboard.
Sharon Liu
 
Webinar: World's Smallest Pacemaker
Scintica Instrumentation
 
2025 Insilicogen Company English Brochure
Insilico Gen
 

Java input Scanner

  • 1. University of Kufa Collage of Computer Science and Mathematics Lecture 3 ‫م‬ . ‫االمين‬ ‫الحسن‬ ‫عبد‬ ‫هدى‬ ‫م‬
  • 2.  The Scanner class is used to get user input, and it is found in the java.util package.  To use the Scanner class, create an object of the class and use any of the available methods found in the Scanner class documentation. In our examples, we will use the nextLine() method, which is used to read Strings: Java User Input (Scanner) the nextInt () method, which is used to read int the nextLine () method, which is used to read string
  • 3. Java User Input (Scanner) import java.util.Scanner; // Import the Scanner class class MyClass { public static void main(String[] args) { Scanner myObj = new Scanner(System.in); // Create a Scanner object System.out.println("Enter username"); String userName = myObj.nextLine(); // Read user input System.out.println("Username is: " + userName); // Output user input } }
  • 4. Java User Input (Scanner) import java.util.Scanner; // Import the Scanner class class MyClass { public static void main(String[] args) { Scanner myObj = new Scanner(System.in); // Create a Scanner object System.out.println("Enter username"); String userName = myObj.nextLine(); // Read user input System.out.println("Username is: " + userName); // Output user input } }
  • 5. Java User Input (Scanner)
  • 6. Java User Input (Scanner)
  • 7.  Some programming statements allow us to make decisions and perform repetitions  These decisions are based on boolean expressions (also called conditions) that evaluate to true or false  The order of statement execution is called the flow of control Flow of Control
  • 8.  A conditional statement lets us choose which statement will be executed next  They are sometimes called selection statements  Conditional statements give us the power to make basic decisions  The Java conditional statements are the:  if and if-else statement  switch statement Flow of Control
  • 9. The if Statement  Let's now look at the if statement in more detail  The if statement has the following syntax: if ( condition ) statement; if is a Java reserved word The condition must be a boolean expression. It must evaluate to either true or false. If the condition is true, the statement is executed. If it is false, the statement is skipped.
  • 10. Logic of an if statement condition evaluated false statement true
  • 11.  A condition often uses one of Java's equality operators or relational operators, which all return boolean results: ==equal to !=not equal to < less than > greater than <=less than or equal to >=greater than or equal to  Note the difference between the equality operator (==) and the assignment operator (=) Boolean Expressions
  • 12.  An if statement with its boolean condition: if (sum > MAX) delta = sum – MAX;  First, the condition is evaluated: the value of sum is either greater than the value of MAX, or it is not  If the condition is true, the assignment statement is executed; if it isn't, it is skipped Boolean Expressions
  • 13. //******************************************************************** // Age.java Author: Lewis/Loftus // // Demonstrates the use of an if statement. //******************************************************************** import java.util.Scanner; public class Age { //----------------------------------------------------------------- // Reads the user's age and prints comments accordingly. //----------------------------------------------------------------- public static void main (String[] args) { final int MINOR = 21; Scanner scan = new Scanner (System.in); System.out.print ("Enter your age: "); int age = scan.nextInt(); continue
  • 14. continue System.out.println ("You entered: " + age); if (age < MINOR) System.out.println ("Youth is a wonderful thing. Enjoy."); System.out.println ("Age is a state of mind."); } }
  • 15. continue System.out.println ("You entered: " + age); if (age < MINOR) System.out.println ("Youth is a wonderful thing. Enjoy."); System.out.println ("Age is a state of mind."); } } Sample Run Enter your age: 47 You entered: 47 Age is a state of mind. Another Sample Run Enter your age: 12 You entered: 12 Youth is a wonderful thing. Enjoy. Age is a state of mind.
  • 16. Logical Operators  Boolean expressions can also use the following logical operators: ! Logical NOT && Logical AND || Logical OR  They all take boolean operands and produce boolean results  Logical NOT is a unary operator (it operates on one operand)  Logical AND and logical OR are binary operators (each operates on two operands)
  • 17. Logical NOT  The logical NOT operation is also called logical negation or logical complement  If some boolean condition a is true, then !a is false; if a is false, then !a is true  Logical expressions can be shown using a truth table: a !a true false false true
  • 18. Logical AND and Logical OR  The logical AND expression a && b is true if both a and b are true, and false otherwise  The logical OR expression a || b is true if a or b or both are true, and false otherwise
  • 19. Logical AND and Logical OR  A truth table shows all possible true-false combinations of the terms  Since && and || each have two operands, there are four possible combinations of conditions a and b a b a && b a || b true true True true true false false true false true false true false false false false
  • 20. Logical Operators  Expressions that use logical operators can form complex conditions if (total < MAX+5 && !found) System.out.println ("Processing…");  All logical operators have lower precedence than the relational operators  The ! operator has higher precedence than && and ||
  • 21. The if-else Statement  An else clause can be added to an if statement to make an if-else statement if ( condition ) statement1; else statement2;  If the condition is true, statement1 is executed; if the condition is false, statement2 is executed  One or the other will be executed, but not both
  • 23. Logic of an if-else statement condition evaluated false statement2 statement true
  • 24. Nested if Statements  The statement executed as a result of an if or else clause could be another if statement  These are called nested if statements  An else clause is matched to the last unmatched if (no matter what the indentation implies)  Braces can be used to specify the if statement to which an else clause belongs  See MinOfThree.java
  • 28. Switch Case statement  Switch case statement is used when we have number of options (or choices) and we may need to perform a different task for each choice.  The syntax of Switch case statement looks like this
  • 31. Switch Case Flow Diagram  First the variable, value or expression which is provided in the switch parenthesis is evaluated and then based on the result, the corresponding case block is executed that matches the result.
  • 33. Break statement in Switch Case  Break statement is optional in switch case but you would use it almost every time you deal with switch case. Before we discuss about break statement, Let’s have a look at the example below where I am not using the break statement:
  • 34. Break statement in Switch Case: Example
  • 35. Break statement in Switch Case: Example
  • 36. Break statement in Switch Case: Example In the above program, we have passed integer value 2 to the switch, so the control switched to the case 2 , revewoh ew nod ’ t have break statement after the case 2 that caused the flow to pass to the subsequent cases till the end . The solution to this problem is break statement Break statements are used when you want your program-flow to come out of the switch body. Whenever a break statement is encountered in the switch body, the execution flow would directly come out of the switch, ignoring rest of the cases Let’s take the same example but this time with break statement.