Decisions in Java IF Statements

Similar documents
Oct Decision Structures cont d

Decisions in Java Nested IF Statements

Conditionals. For exercises 1 to 27, indicate the output that will be produced. Assume the following declarations:

Decisions in Java The IF Statement. In performing a task, we often want to take one of two possible actions depending on the conditions at the time.

4. If the following Java statements are executed, what will be displayed?

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java

Full file at

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Gaddis: Starting Out with Java: From Control Structures through Objects, 6/e

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Starting Out with Java: From Control Structures through Data Structures 3e (Gaddis and Muganda) Chapter 2 Java Fundamentals

Computational Expression

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Programming with Java

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Basic data types. Building blocks of computation

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic

Getting started with Java

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

Control Structures in Java if-else and switch

Zheng-Liang Lu Java Programming 45 / 79

Java Basic Programming Constructs

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

CS 102 / CS Introduction to Programming Midterm Exam #1 - Prof. Reed Fall 2010

CS Introduction to Programming Midterm Exam #1 - Prof. Reed Fall 2009

SAMPLE QUESTIONS FOR DIPLOMA IN INFORMATION TECHNOLOGY; YEAR 1

Programming Projects: 2.1, 2.3, 2.4, 2.7, 2.8, 2.13

McGill University School of Computer Science COMP-202A Introduction to Computing 1

Lesson 2A Data. Data Types, Variables, Constants, Naming Rules, Limits. A Lesson in Java Programming

Chapter 2: Using Data

Software and Programming 1

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

CS 101 Fall 2006 Midterm 3 Name: ID:

Datatypes, Variables, and Operations

I. True/False: (2 points each)

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

Lecture Set 2: Starting Java

Java Identifiers, Data Types & Variables

Important Java terminology

CSE 201 JAVA PROGRAMMING I. Copyright 2016 by Smart Coding School

Loops. CSE 114, Computer Science 1 Stony Brook University

Lecture Set 2: Starting Java

Array. Prepared By - Rifat Shahriyar

CS Introduction to Programming Midterm Exam #1 - Prof. Reed Spring 2009

Object-Oriented Programming

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

Programming: Java. Chapter Objectives. Control Structures. Chapter 4: Control Structures I. Program Design Including Data Structures

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics

4 Programming Fundamentals. Introduction to Programming 1 1

Program Fundamentals

Exam 1. CSC 121 Spring Lecturer: Howard Rosenthal. March 1, 2017

Chapters 1-4 Summary. Syntax - Java or C? Syntax - Java or C?

CMPT 125: Lecture 3 Data and Expressions

Over and Over Again GEEN163

Chapter 02: Using Data

Java Coding 2. Decisions, decisions!

PROGRAMMING FUNDAMENTALS

CHAPTER 5 VARIABLES AND OTHER BASIC ELEMENTS IN JAVA PROGRAMS

CS Week 5. Jim Williams, PhD

Chapter 4 Fundamental Data Types. Big Java by Cay Horstmann Copyright 2009 by John Wiley & Sons. All rights reserved.

Strings. Strings and their methods. Dr. Siobhán Drohan. Produced by: Department of Computing and Mathematics

Outline. Overview. Control statements. Classes and methods. history and advantage how to: program, compile and execute 8 data types 3 types of errors

cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1

data_type variable_name = value; Here value is optional because in java, you can declare the variable first and then later assign the value to it.

A very simple program. Week 2: variables & expressions. Declaring variables. Assignments: examples. Initialising variables. Assignments: pattern

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

CMSC131. Introduction to your Introduction to Java. Why Java?

Ans: Store s as an expandable array of chars. (Double its size whenever we run out of space.) Cast the final array to a String.

Java Flow of Control

First Java Program - Output to the Screen

Conditionals and Loops

Lecture Set 4: More About Methods and More About Operators

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

Conditional Programming

Outline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail.

2/9/2012. Chapter Four: Fundamental Data Types. Chapter Goals

Introduction to Software Development (ISD) Week 3

Data types Expressions Variables Assignment. COMP1400 Week 2

C212 Early Evaluation Exam Mon Feb Name: Please provide brief (common sense) justifications with your answers below.

Programming Lecture 3

Assignment 2.4: Loops

1 class Lecture2 { 2 3 "Elementray Programming" / References 8 [1] Ch. 2 in YDL 9 [2] Ch. 2 and 3 in Sharan 10 [3] Ch.

1007 Imperative Programming Part II

Control Structures in Java if-else and switch

(A) 99 ** (B) 100 (C) 101 (D) 100 initial integers plus any additional integers required during program execution

COMP Primitive and Class Types. Yi Hong May 14, 2015

Logical Operators and switch

Java Foundations: Introduction to Program Design & Data Structures, 4e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2

int: integers, no fractional part double: floating-point numbers (double precision) 1, -4, 0 0.5, , 4.3E24, 1E-14

AL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: Text-printing program. CSC 209 JAVA I

CSE115 / CSE503 Introduction to Computer Science I Dr. Carl Alphonce 343 Davis Hall Office hours:

Bits, Words, and Integers

5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont.

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

printf( Please enter another number: ); scanf( %d, &num2);

Transcription:

Boolean Values & Variables In order to make decisions, Java uses the concept of true and false, which are boolean values. Just as is the case with other primitive data types, we can create boolean variables to hold these values. boolean readytoprogram = true; Boolean Expressions A boolean expression is similar to a mathematical expression, except that the result is true or false, rather than a numeric value. To create a boolean expression, we use the relational operators to compare the values of various data types, such as integers, floats, characters, or strings, using a relational expression. Relational Operator Meaning Example Result == is equal to 5 == 5 TRUE!= is not equal to 5!= 5 FALSE < is less than 3 < 7 TRUE <= is less than or equal to 4 <= 4 TRUE > is greater than 3 > 7 FALSE >= is greater than or equal to 7 >= 3 TRUE The following rules apply to the use of relational operators with different data types: 1. Values of any of the primitive numeric data types (e.g., int, float, and all their variations) can be used with any of the relational operators. 2. Boolean values can only be tested as equal to or not equal to. 3. Values of type char are ordered according to the Unicode encoding system. A character the occurs earlier in the system is less than a character that occurs later in the system. a) For alphabetic characters, this means that 'a' is less than 'z', and 'A' is less than 'Z', as expected. b) In the Unicode system, all uppercase letters occur earlier than all lowercase letters. Thus we get the relational ordering of: 'A' < 'B' < 'C' <... < 'Z' < 'a' < 'b' < 'c' <... <'z' c) Representing numbers as characters, such as when you type on a keyboard, keeps the same ordering, so that '0' < '1' < '2' <... < '9'. Page 1 of 6

Comparing Strings The relational operators used with the primitive data types should not be used to compare strings. Recall that a String variable does not actually contain the string, but only the location (address) of the string in memory. Thus any comparison between strings using relational operators would actually be comparing two addresses, rather than the String values. Java provides a number of methods for comparing strings, but for now we will introduce only the equals method. This is a String method, which means it can be called from any String variable. For example, given the declaration String s = "Same"; then the equals method would yield the following results: a) s.equals("same") will return true b) s.equals("same") will return false because 'S' is not equal to 's' c) s.equals("same ") will return false because of the spaces at the end of the word Boolean Operators It is possible to combine two or more boolean values, variables, or expressions into a more complicated boolean expression using the boolean operators. Unlike the relational operators, the boolean operators can only work on boolean values. You can use a relational operator to compare any data type, which forms a boolean expression. Multiple boolean expressions can be combined using boolean operators. The boolean operators are summarized in the following table. boolean value not p p AND q p OR q p q!p p && q p q TRUE TRUE FALSE TRUE TRUE TRUE FALSE FALSE FALSE TRUE FALSE TRUE TRUE FALSE TRUE FALSE FALSE TRUE FALSE FALSE Page 2 of 6

1.!p (not p) has the true/false value opposite to p. 2. p && q (p AND q) is true if and only if both p and q are both true. 3. p q (p OR q) is true if p is true, q is true, or both p and q are true. One Choice IF-THEN Statements if (<boolean expression>) <statements> The simplest decision is to choose between doing something, or doing nothing. In this general code outline, the <boolean expression> may be quite simple or very sophisticated. Similarly, the <statements> could be a single line of Java code, or a very complicated block of code. Nonetheless, there is a single decision here if the boolean expression evaluates to true, the statements will be executed. If the expression is false, no code from this block is executed. Two Choices IF-THEN-ELSE Statements Rather than doing nothing, it is far more common to use our decision to choose between two possible options one for true, one for false. The additional code, for the false condition, is placed within the block of the statement. This is the most commonly occurring decision statement. class IfDemo public static void main (String[] args) System.out.print("Please give one integer: "); int first = In.getInt(); System.out.print("and a second: "); int second = In.getInt(); if (first == second) System.out.println("The values are equal"); System.out.println("The values are not equal"); Page 3 of 6

Many Choices Nested IF Statements Decisions in Java IF Statements It is possible to make more than two choices with multiple if statements: if (x < 0) System.out.println("value is negative"); if (x > 0) System.out.println("value is positive"); if (x == 0) System.out.println("value is zero"); This code involves three tests, which may not seem significant now, but inefficient testing of conditions is one of the major sources of slow and inefficient programs. The following code improves the efficiency by reducing the code to a maximum of two comparisons using nesting. if (x < 0) System.out.println("value is negative"); if (x > 0) System.out.println("value is positive"); System.out.println("value is zero"); An alternate format is also available which has a more linear appearance than the nested code. if (x < 0) System.out.println("value is negative"); if (x > 0) System.out.println("value is positive"); // (x == 0) is the only remaining option System.out.println("value is zero"); Page 4 of 6

Exercises 1. Study this program and then answer the questions that follow it. Try it on paper first, and then code the program to check your answers. class ChipChoice public static void main (String [] args) System.out.println("Preferred flavour? (first letter only) "); char flavour = In.getChar(); System.out.println("Preferred style? (first letter only)"); char style = In.getChar(); System.out.print("The client preferred "); if (flavour == 'B') System.out.print("bar-b-que"); if (flavour == 'V') System.out.print("vinegar"); System.out.print("other"); if (style == 'C') System.out.print(", crinkled"); if (style == 'R') System.out.print(", regular"); System.out.println(" chips."); What would the program print given each set of data as input? (a) V C (b) B R (c) V T (d) B C (e) C V (f) v r 2. How would you modify the ChipChoice program so that it would accept both upper case and lower case letters in the responses from the user? Page 5 of 6

3. One way of giving a direction is to simply use one of the letters N, E, S, or W, indicating the nearest compass point. Another way is to give a bearing as a number from 0 to 359 (since 360 would be back to 0 again). A bearing of 0 corresponds to N, a bearing of 90 corresponds to E, and so on. Write a program that prompts the user for a bearing from 0 to 359 and prints the corresponding letter of he compass point nearest to the bearing. For example, input of 73 is between N and E, but it is closer to E, so the program should output E. Bearings exactly halfway between two compass points should produce either N or S (never E or W). 4. In the country of Rahmania, the cost of mailing a letter is 40 sinas for letters up to 30 grams. Between 30 g and 50 g, it is 55 sinas. Between 50 g and 100 g, it is 70 sinas. Over 100 g, it costs 70 sinas plus an additional 25 sinas for each additional 50 g (or part thereof). For example, 101 grams would cost 70 + 25 = 95 sinas. 149 g would also cost 95 sinas, because both of these packages only use the first 50 g over 100 g. Write a program that prompts the user for a mass and then gives the cost of mailing a letter having that mass. Page 6 of 6