Docsity

Lecture 2 (|CSEN202|) Introduction to Computer Programming, Lecture notes of Physics

Partial preview of the text

Download Lecture 2 (|CSEN202|) Introduction to Computer Programming and more Lecture notes Physics in PDF only on Docsity!

CSEN 202

Introduction to Computer Programming

Lecture 2 User inputs and conditionals Dr. Milad Ghantous Spring 2023 GUC

Part 1

User inputs

The Scanner class

  • (^) Any time you want the user input, you need to create a new instance of the Scanner object, followed by one of the scan methods to get the input.

Step 1 Scanner sc = new Scanner(System.in);

Step 2 (^) int x = sc.nextInt();

Can we only read integers?

  • (^) No! Scanner has many

methods to read all kind of

inputs.

Entering Strings

  • (^) Two methods are available: next() nextLine()
  • (^) Reads 1 string
  • (^) or the first string in a

sentence.

  • (^) Reads an entire line

(sentence) until the

carriage return (the

enter)

Examples: Strings Scanner sc = new Scanner(System.in); System.out.print("Enter a value please:"); String x = sc.next(); System.out.println("you entered " + x); Scenario 1 Scenario 2 Scanner sc = new Scanner(System.in); System.out.print("Enter a value please:"); String x = sc. nextLine (); System.out.println("you entered " + x); Scenario 1 Scenario 2

if/else

  • (^) Similar to python, java has its if else structures to evaluate conditions.
  • (^) There is no elif in java. Instead you write else if
  • (^) There are no indentations in java, except for visually organizing your code but doesn’t affect the execution.

if/else syntax if (condition) {

// your then statement(s)

} if (condition) { // your then statement(s) } else { // your else statement(s) }

Complex Conditions

  • (^) Boolean conjunction: &&
  • (^) Boolean disjunction: ||
  • (^) Boolean Negation:!

Examples Can also be written this way  Can also be written this way  Why does this work you think?

Examples

  • (^) Guess the output removed else To which if does this else belong?
  • (^) In this case, else always follows the latest if (the one closest to it). It’s called the DANGLING else.

Tricky cases

  • (^) Will compile, as java sees that you are using variable z, but java is sure that z is initialized either in if or else - (^) By adding the if inside the else, z might not be initialized. In this example, we know it will, but java doesn’t know. Since z is not used afterwards, it will compile - (^) Will not compile! - (^) Java sees you are using z, but z might not be initialized because the else contains an if that might be also false.

Refactoring if conditionals Case 2 Example 1

Refactoring if conditionals Case 2 Example 2 Are those equivalent?