Fundamentals of Programming. Laboratory 3 Selection structures, designing selections, nested selection

Similar documents
System.out.println("\nEnter Product Number 1-5 (0 to stop and view summary) :

Introduction to Java

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

Part I. Multiple Choice Questions (2 points each):

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

J a v a Quiz (Unit 3, Test 0 Practice)

AP Computer Science Java Mr. Clausen Program 9A, 9B

Sample CSE8A midterm Multiple Choice (circle one)

Chapter 2: Elements of Java

1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

MIDTERM 1 REVIEW WRITING CODE POSSIBLE SOLUTION

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

Chapter 5. Selection 5-1

AP Computer Science Static Methods, Strings, User Input

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

In this Chapter you ll learn:

Topic 11 Scanner object, conditional execution

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

Building Java Programs

COSC Introduction to Computer Science I Section A, Summer Question Out of Mark A Total 16. B-1 7 B-2 4 B-3 4 B-4 4 B Total 19

Java Basics: Data Types, Variables, and Loops

Conditional Statements Summer 2010 Margaret Reid-Miller

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

- User input includes typing on the keyboard, clicking of a mouse, tapping or swiping a touch screen device, etc.

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

Iteration CHAPTER 6. Topic Summary

Object Oriented Software Design

Part 1 Foundations of object orientation

A.2. Exponents and Radicals. Integer Exponents. What you should learn. Exponential Notation. Why you should learn it. Properties of Exponents

Chapter 2 Introduction to Java programming

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

Object Oriented Software Design

CS114: Introduction to Java

Java 進 階 程 式 設 計 03/14~03/21

While and Do-While Loops Summer 2010 Margaret Reid-Miller

LOOPS CHAPTER CHAPTER GOALS

Arrays. Introduction. Chapter 7

Accentuate the Negative: Homework Examples from ACE

Chapter One Introduction to Programming

Dŵr y Felin Comprehensive School. Perimeter, Area and Volume Methodology Booklet

Lecture 1 Introduction to Java

Explain the relationship between a class and an object. Which is general and which is specific?

Handout 3 cs180 - Programming Fundamentals Spring 15 Page 1 of 6. Handout 3. Strings and String Class. Input/Output with JOptionPane.

PIC 10A. Lecture 7: Graphics II and intro to the if statement

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

Problem 1. CS 61b Summer 2005 Homework #2 Due July 5th at the beginning of class

Introduction to Programming

Q&As: Microsoft Excel 2013: Chapter 2

Perl in a nutshell. First CGI Script and Perl. Creating a Link to a Script. print Function. Parsing Data 4/27/2009. First CGI Script and Perl

Programming Fundamentals I CS 110, Central Washington University. November 2015

CompSci 125 Lecture 08. Chapter 5: Conditional Statements Chapter 4: return Statement

Using Format Manager For Creating Format Files

Performing Simple Calculations Using the Status Bar

Variables, Constants, and Data Types

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

Math 0980 Chapter Objectives. Chapter 1: Introduction to Algebra: The Integers.

Chapter 2 Elementary Programming

CASCADING IF-ELSE. Cascading if-else Semantics. What the computer executes: What is the truth value 1? 3. Execute path 1 What is the truth value 2?

Lies My Calculator and Computer Told Me

Building Java Programs

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

MATH 60 NOTEBOOK CERTIFICATIONS

Understanding class definitions

Scanner sc = new Scanner(System.in); // scanner for the keyboard. Scanner sc = new Scanner(System.in); // scanner for the keyboard

The Interface Concept

Inventory Costing Repair and Restoration

Token vs Line Based Processing

3 Data Properties and Validation Rules

Arc Length and Areas of Sectors

To Evaluate an Algebraic Expression

MATLAB Programming. Problem 1: Sequential

Chapter 2. println Versus print. Formatting Output withprintf. System.out.println for console output. console output. Console Input and Output

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Introduction to Python

Laboratory Assignments of OBJECT ORIENTED METHODOLOGY & PROGRAMMING (USING C++) [IT 553]

Introduction to Java. CS 3: Computer Programming in Java

Answer Key for California State Standards: Algebra I

ALGEBRA. sequence, term, nth term, consecutive, rule, relationship, generate, predict, continue increase, decrease finite, infinite

AP * Statistics Review. Descriptive Statistics

Conditionals (with solutions)

SAT Math Facts & Formulas Review Quiz

Reading Input From A File

Supplemental Worksheet Problems To Accompany: The Pre-Algebra Tutor: Volume 1 Section 9 Order of Operations

Sources: On the Web: Slides will be available on:

Pseudo code Tutorial and Exercises Teacher s Version

Data Structures In Java

7-1. This chapter explains how to set and use Event Log Overview Event Log Management Creating a New Event Log...

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Factoring and Applications

CS170 Lab 11 Abstract Data Types & Objects

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

(Eng. Hayam Reda Seireg) Sheet Java

VHDL Test Bench Tutorial

Joins Joins dictate how two tables or queries relate to each other. Click on the join line with the right mouse button to access the Join Properties.

Order of Operations More Essential Practice

MS Access: Advanced Tables and Queries. Lesson Notes Author: Pamela Schmidt

AP Computer Science Java Subset

JavaScript: Arrays Pearson Education, Inc. All rights reserved.

Transcription:

Fundamentals of Programming Laboratory 3 Selection structures, designing selections, nested selection

DECISION STRUCTURES allow programs to follow different courses of action or execute different tasks depending on the data values

CONDITIONALS cause something to happen in a program only if a specific condition is met If a condition is true then do something, else do something else usually a relational operator is used to compare the two properties

RELATIONAL OPERATORS < less than > greater than = = equal to <= less than or equal to >= greater than or equal to!= not equal to

IF STATEMENTS The most basic way to test a condition in a Java program works along the same lines, testing to see whether a condition is true or false, and taking action only if the condition is true boolean variable type is used to store only two possible values: true or false

IF STATEMENTS Single - option structure: if (expression) { statement(s); }

IF STATEMENTS Example: int a = 1; if(a==1) { System.out.print( a equals 1 ); } /*The body of an if statement (printing a equals to 1 ) will be run only if the condition is true (a is equal to 1). */

IF ELSE STATEMENTS used when you want to do something if a condition is true and do something else if the condition is false

IF ELSE STATEMENTS Double - option structure: if (expression) { } // code to perform if true else { } // code to perform if false

IF ELSE STATEMENTS Example: int a = 1; if (a == 1) { System.out.print("a equals 1"); } else { System.out.print("a is not equal to 1"); }

IF ELSE STATEMENTS Multi alternative decision: We can put together several different if and else statements to handle a variety of conditions

IF ELSE IF - STATEMENTS if (b==0) { System.out.print("b is 0"); } else if (b==1) System.out.print("b is 1"); else if (b=>2) { System.out.print("b is greater than 2"); } else { System.out.print( b value is negative ); }

SMALL REVIEW What's wrong with the code below? if (i = 1) { /* do something */ } ORAL EXERCISE

SWITCH STATEMENTS Another way to create in Java multi alternative decision is to use a switch structure, very useful when you wish to avoid a lot of IF statements

SWITCH STATEMENTS switch (integervariable) { case 1: System.out.println( 1"); //break; case 2: System.out.println( 2"); break; case 3: System.out.println( 3"); break; default: //optional System.out.println( Wrong number!"); }

SWITCH STATEMENTS switch (intvariable) { case 1: //no break, so continues to next case case 2: System.out.println( 1 or 2"); break; case 3: System.out.println( 3"); break; default: //optional System.out.println( Wrong number!"); }

SWITCH STATEMENTS The first line of the switch statement specifies the variable that will be tested. Then the switch statement uses the brace brackets to form a block statement. Each of the case statements checks the test variable in the switch statement against a specific value. It is impossible to test in switch structure other conditions than = =

SWITCH STATEMENTS break statement causes that no other part of the switch statement will be considered. The break statement tells the computer to break out of the switch statement. The default statement is used as a catch-all if none of the preceding case statements contained a break.

TERNARY OPERATOR You can use the ternary operator when you just want to assign a value or display a value based on a simple conditional test. if (expression) else a = somevalue; a = anothervalue; Instead you can write: a = (expression)? somevalue : othervalue ;

TERNARY OPERATOR STRUCTURE The condition to test, surrounded by parentheses (expression) followed by a question mark? The value use if the condition is true, then a colon : The value to use if condition is false variable = (expression)? somevalue : othervalue ;

TERNARY OPERATOR STRUCTURE Example 1: int result = 10; int numberofpoints; numberofpoints = (result > 5)? 1 : 0; If result value is greater than 5 number of given points is 1 else there is no given points.

TERNARY OPERATOR STRUCTURE Example 2: String gender = "female"; System.out.print( (gender.equals("female"))? "Ms." : "Mr." ); /* text variables cannot be compared using ==, instead the.equals() method must be used */

NESTED DECISION STATEMENTS Example [Sanchez]:

Java Code: Scanner input = new Scanner(System.in); int userinputvalue; userinputvalue = input.nextint(); if ((userinputvalue = = 1) (userinputvalue = = 2)) { System.out.println( BEEP BEEP ); if(userinputvalue = = 2) { System.out.print( Input = 2 ); } } NOTE: means OR, && means AND.

EXERCISE 1a If the variable angle is equal to 90 degrees, print the message The angle is a right angle ; otherwise, print the message The angle is not a right angle. BOARD EXERCISE

EXERCISE 1b If the temperature is above 100 degrees, display the message above boiling ; if it is equal to 100 display the message boiling ; otherwise display below boiling BOARD EXERCISE

EXERCISE 1c If the variable number is positive, add number to possum (increment possum by number); otherwise, add number to negsum BOARD EXERCISE

EXERCISE 1d If the variable slope is less than 0.5 set the flag to zero; otherwise, set flag to one BOARD EXERCISE

EXERCISE 1e If the difference between the variables num1 and num2 is less than 0.001, set the variable approx to zero; otherwise, calculate approx as the quantity (num1 num2)/ 2.0. BOARD EXERCISE

EXERCISE 1f If the difference between the variables temp1 and temp2 exceeds 2.3 degrees, calculate the variable error as (temp1 temp2) * factor BOARD EXERCISE

EXERCISE 1g If the variable x is greater than the variable y and the variable z is less than 20, read in a value for the variable p; BOARD EXERCISE

EXERCISE 1h If the variable distance is greater then 20 and it is less than 35, read in value for the variable time. BOARD EXERCISE

EXERCISE 2 Write a Java program that displays either the message I feel great today! Or I feel down today! depending on the input. If the input is the integer 1, entered in the variable choice, the first message should be displayed; otherwise, the second message should be displayed PROGRAMMING EXERCISE

EXERCISE 3 A senior salesperson is paid $400 a week and a junior salesperson $275 a week. Write a Java program that accepts as input a salesperson s status in a String variable. If the status equals s, the senior person s salary should be displayed; otherwise, the junior person s salary should be output. Note: String status = input.nextline(); if (status.equals( s )) PROGRAMMING EXERCISE

EXERCISE 4 Write a Java program that displays a student s status based on the following codes: Code Student Status 1. Freshman 2. Sophomore 3. Junior 4. Senior 5. Master program 6. Doctoral program Your program should accept the code number as a user entered input value and based on this value display the correct student status. If an incorrect code is entered, your program should display the string An incorrect code was entered. PROGRAMMING EXERCISE

EXERCISE 5 Each disk drive in a shipment of these devices is stamped with a code from 1 through 4, which indicates a drive manufacturer as follows Code Disk Drive Manufacturer 1. 3M Corporation 2. Maxell Corporation 3. Sony Corporation 4. Verbatim Corporation Write a Java program that accepts the code number as an input and, based on the value entered, displays the correct disk drive manufacturer. Note: Use a different method than in Ex.4 PROGRAMMING EXERCISE

HOMEWORK (option 1) Write a Java program that calculates the areas of different geometrical figures. Your program should display menu as below: ---------------------- GEOMETRICAL FIGURE CALCULATIONS ---------------------- Figure: 1. Circle 2. Triangle 3. Ellipse 4. Trapezium ----------------------- Type number desired ----------------------- After choosing the option program should ask the user for the data required (height, width, radius etc.) to calculate the area. Program displays the result of figure field calculation based on entered data. HOMEWORK EXERCISE

HOMEWORK (option 2) Write a Java program that works like a Magic 8-ball or Futrzak. Your program should ask the user to type a question with a yes/no answer, then display a random answer, example: Will I get a top mark in this class? Not likely Make sure to check if the user typed something (the string is not empty textvar.equals("")) Hint: Use Math.random() to generate a random number 0.0<=x<1.0 multiply the number by 10 and round it to int, then use switch structure. HOMEWORK EXERCISE