Lecture 6. Assignments. Summary - Variables. Summary Program Parts 1/29/18. Reading: 3.1, 3.2, 3.3, 3.4

Similar documents
Lecture 6. Assignments. Java Scanner. User Input 1/29/18. Reading: 2.12, 2.13, 3.1, 3.2, 3.3, 3.4

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

Lecture 5. Assignments. Arithmetic Operations. Arithmetic Operations -Summary 1/24/18. Lab 3: Variables and operations. Read Sections

Programming with Java

Using Java Classes Fall 2018 Margaret Reid-Miller

ECE 122 Engineering Problem Solving with Java

Oct Decision Structures cont d

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on:

Building Java Programs

AP Computer Science A

A variable is a name for a location in memory A variable must be declared

Building Java Programs

Introduction to Computer Programming

More Things We Can Do With It! Overview. Circle Calculations. πr 2. π = More operators and expression types More statements

Lecture Set 2: Starting Java

CS 302: Introduction to Programming

Lecture Set 2: Starting Java

Basic Computation. Chapter 2

Basic Computation. Chapter 2

Building Java Programs. Chapter 2: Primitive Data and Definite Loops

Lecture 9. Assignment. Logical Operations. Logical Operations - Motivation 2/8/18

Programming with Java

Computational Expression

COMP String and Console I/O. Yi Hong May 18, 2015

Full file at

CS313D: ADVANCED PROGRAMMING LANGUAGE

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

Building Java Programs Chapter 2

2: Basics of Java Programming

Hello World. n Variables store information. n You can think of them like boxes. n They hold values. n The value of a variable is its current contents

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

Chapter. Let's explore some other fundamental programming concepts

Exam 1 Prep. Dr. Demetrios Glinos University of Central Florida. COP3330 Object Oriented Programming

CS 302: INTRODUCTION TO PROGRAMMING. Lectures 7&8

Section 2: Introduction to Java. Historical note

CS 106 Introduction to Computer Science I

Building Java Programs

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

Question: Total Points: Score:

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

Lesson 02 Data Types and Statements. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

Building Java Programs Chapter 2. bug. Primitive Data and Definite Loops. Copyright (c) Pearson All rights reserved. Software Flaw.

Building Java Programs Chapter 2

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

Elementary Programming

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Full file at

Chapter 2. C++ Basics

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

We now start exploring some key elements of the Java programming language and ways of performing I/O

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Data Conversion & Scanner Class

COMP 202 Java in one week

CS 106 Introduction to Computer Science I

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Lecture 2: Operations and Data Types

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

Program Elements -- Introduction

Fundamentals of Programming Data Types & Methods

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Please answer the following questions. Do not re-code the enclosed codes if you have already completed them.

COMP 202. Java in one week

Lecture 3 Tao Wang 1

CIS 1068 Design and Abstraction Spring 2017 Midterm 1a

Lecture Notes. System.out.println( Circle radius: + radius + area: + area); radius radius area area value

Lesson 02 Data Types and Statements. MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

CS111: PROGRAMMING LANGUAGE II

What did we talk about last time? Examples switch statements

COMP 202. Built in Libraries and objects. CONTENTS: Introduction to objects Introduction to some basic Java libraries string

COMP 202 Java in one week

Object Oriented Programming with Java

CS 106 Introduction to Computer Science I

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

Course Outline. Introduction to java

Getting started with Java

Chapter Overview. C++ Basics. Variables and Assignments. Variables and Assignments. Keywords. Identifiers. 2.1 Variables and Assignments

2.5 Another Application: Adding Integers

Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

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

COSC 123 Computer Creativity. Introduction to Java. Dr. Ramon Lawrence University of British Columbia Okanagan

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

Chapter 4: Conditionals and Recursion

Computational Expression

Entry Point of Execution: the main Method. Elementary Programming. Compile Time vs. Run Time. Learning Outcomes

Primitive Data, Variables, and Expressions; Simple Conditional Execution

What methods does the String class provide for ignoring case sensitive situations?

Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

Midterm Exam 2 Thursday, November 15th, points (15% of final grade) Instructors: Jim Williams and Marc Renault

Basics of Java Programming

Topic 4 Expressions and variables

Logic & program control part 2: Simple selection structures

Chapter 2 ELEMENTARY PROGRAMMING

The for Loop, Accumulator Variables, Seninel Values, and The Random Class. CS0007: Introduction to Computer Programming

Lesson 7 Part 2 Flags

Operators. Java operators are classified into three categories:

Transcription:

Assignments Lecture 6 Complete for Project 1 Reading: 3.1, 3.2, 3.3, 3.4 Summary Program Parts Summary - Variables Class Header (class name matches the file name prefix) Class Body Because this is a program, the body contains a main method. Main method header Main method body Special Characters we have seen so far: - Braces define a class body, method body () - Parentheses define the parameters to a method ; - Semi colon end of a statement // - Start a 1 line comment - Pair of double quotes enclose a string of letters - Use single quotes to enclose a character (a-z, A-Z, 0-9, punctuation) Declaration: type name ; Assignment: Variable name on left Operator = in the middle Value on the right Scope lifespan of the variable Start of lifespan - Declaration End of lifespan Closing brace of code block where declared 1

Summary - Arithmetic Operations There are 5 common operations: Addition: + Subtraction: - Multiplication: * Division: / Recall: A B = Quotient * B + Remainder If both operands are integer: produces the quotient Else same as A B Modulus: % (produces the remainder) Summary - Types Primitive Types Variables store the value byte, short, int, long, float, double, boolean, char Reference Types Variables store references to objects, objects stored where in memory String, Scanner, Double, Integer Call methods on object using the dot operator String str = hello ; int numchars = str.length(); Summary - String Declare String str; Create str = Mary ; str = new String( Mary ); Methods to call: int length(); String tolowercase(); String touppercase(); char charat(int position); // position = 0, length - 1 Summary Program Output String (cont) Operator + concatenates two Strings together Concatenate a String and a number and store result in a new String Using print and println to output information to a program. int number = 17; String color = Green ; System.out.println(number); // outputs 17, value of variable System.out.println(color); // outputs Green, value stored in // object referenced by color 2

Summary Scanner (Program Input) Summary - Conversions Import Statement Before class header, add: import java.util.scanner; Declare Scanner keyboard; Create keyboard = new Scanner(System.in); Methods to call: String nextline(); double nextdouble(); int nextint(); Given a String, there are two ways to convert it to a numeric value double Double.parseDouble(String); int Integer.parseInt(String); When will the conversion fail? 340 will convert to int or double abc will cause a run time exception 34.2 will convert to a double Decision Structures Conditional Execution Decision structures allow us to modify the flow of a program We can conditionally execute or conditionally skip one or more statements based on a decision In your first Project, you will extend your TaxComputer program to use decision statements to set the state tax rate based on the the clients state of residence. This project will also use decision statements to determine the taxable income and the amount of federal tax owed. Goal: Send a message to all students enrolled in the Spring term who have not yet paid their tuition. Pseudo-Code: If a student is enrolled in at least one class If they have not paid their tuition Email them a message indicating that their tuition is due. The email should include the balance and the due date. How do we write Java code that performs the sequence above? A message should be sent only if a student is enrolled and if they have not paid their tuition. 3

Java if Statement - Example Example: Converting a Score to a letter Grade boolean tuitiondue = true; if (tuitiondue) System.out.println( Pay your tuition! ); The if-block is all the code in red above. Behavior if is a Java keyword. It is followed by parentheses(). Inside the parentheses is a boolean (has the value of true or false). Flow: when tuitiondue has the value of true, the println is executed. when tuitiondue has the value of false, the println is not executed. Write a program that asks the user to enters 2 exam scores, computes and outputs the average. If the average is at least 97, print a congratulations banner. Pseudo Code Print message for score 1 Read score 1, convert to double Print message for score 2, Read score 2, convert to double Compute average Output average Print message for score 1 Read score 1, convert to double Scanner keyboard = new Scanner(System.in); System.out.print( Please enter the first score: ); String input = keyboard.nextline(); double score1 = Double.parseDouble(input); Compute average Output average double avg = (score1 + score2) / 2; 4

Use a relational operator to compare the value of the variable avg to the value 97. Result is a boolean Read expressions from left to right! Let a and b be two different primitive variables. Assume they have the same primitive type: boolean result = a < b; // result is true if a less than b boolean result = a > b; // result is true if a greater than b boolean result = a <= b; // result is true if a less than, or equal to, b boolean result = a >= b; // result is true if a greater than, or equal to, b boolean result = a == b; // result is true if a equals b boolean result = a!= b; // result is true if a is not equal to b Use a relational operator to compare the value of the variable avg to the value 97. Which is the correct operator to use? at least à greater than or equal à >= if (avg >= 97) System.out.println( Great Job!!! ); Note that we put the expression inside the parentheses. this is the most common approach. Read this as: boolean tmp = avg >= 97; If (tmp).. Java if Statement Java if Statement - continued General Form if (booleanexpression) statement; A booleanexpression evaluates to true or false You can use a boolean variable You can use an expression with a relational operator If we want to conditionally execute multiple statements, use braces to form a code block if (booleanexpression) statement1; statement2; statement3; The if block is the code in red Flow: When the expression is true, the code block defined by the braces is executed When the expression is false, the code block is skipped 5

Last Note on Relational Operators Compute average Output average double avg = (score1 + score2) / 2; if (avg >= 97) System.out.println( Great Job!!! ); if (avg < 97) Relational operators can be used primitive types byte, short, int, long, double, float and char and boolean Let a and b be two different primitive variables. Assume they have the same primitive type: boolean result = a < b; // result is true if a less than b boolean result = a > b; // result is true if a greater than b boolean result = a <= b; // result is true if a less than, or equal to, b boolean result = a >= b; // result is true if a greater than, or equal to, b boolean result = a == b; // result is true if a equals b boolean result = a!= b; // result is true if a is not equal to b See pages 120-121 for examples with char variables. Java if- Statement Java supports a structure that, with one test, allows you to select between two different code paths. if (booleanexpression) statement1; or code block statement2; or code block Flow: When the boolean expression evaluates to true, statement1 is executed. Otherwise, statement 2 is executed. With an if- structure, one of the two statements is always executed. Compute average Output average double avg = (score1 + score2) / 2; if (avg >= 97) System.out.println( Great Job!!! ); 6

Example: Summary if and if- statement Write a Java statement that assigns to the variable rate, the value of 0.20 if the variable income is at least 10000. Otherwise, set the rate to a value of 0.05. if statement: when expression evaluates to true, execute statement if (expression) statement; or code block double rate; // declare the variable, value unknown if (income >= 10000) // why >=? rate = 0.20; rate = 0.05; if statement: when expression evaluates to true, execute statement1 otherwise, execute statement2. if (expression) statement1; or code block statement2; or code block Java if- if [ ] - Example: Using only if- statements To test a series of conditions, you can use nested if- statements. However, it is often easier to use the if statement. Goal: Output a message the prints a letter grade based on the average of 3 exam scores. Use a straight scale. One solution is: if average at least 90, output A if average at least 80, output B if average at least 70, output C output not passing. 7

if (avg >= 90) System.out.println( A ); if (avg >= 80) System.out.println( B ); if (avg >= 70) System.out.println( C ); System.out.println( Not passing ); Example: Using only if- if statements Another solution is: if average at least 90, output A if average at least 80, output B if average at least 70, output C output not passing. Lets write this in Java if (avg >= 90) System.out.println( A ); if (avg >= 80) System.out.println( B ); if (avg >= 70) System.out.println( C ); System.out.println( Not passing ); if (avg >= 90) System.out.println( A ); if (avg >= 80) System.out.println( B ); if (avg >= 70) System.out.println( C ); System.out.println( Not passing ); The if and if keywords are followed by a boolean expression contained in parentheses Only evaluate the expression avg >= 80 when the expression avg >= 90 evaluated to false. Can have as many if clauses as you want. The trailing is optional. 8

if and if- if - statement if statement: when expression evaluates to true, execute statement if (expression) statement; or code block if if statement: when expression evaluates to true, execute statement1 otherwise evaluate anotherexpression. If it evaluates to true, execute statement2 execute statement3. if (expression) statement1; or code block delimited by braces if (anotherexpression) statement2; or code block statement3; or code block A common task in a program is to display a message that asks the user to enter data via the keyboard. The program then reads the data. To display a message, Java programmers use a print or println statement. To read data, Java programmers use a Scanner. Assume: Scanner keyboard; Circle all that are true. a) The variable keyboard is a primitive type. b) The statement creates a Scanner and assigns the value to keyboard: keyboard = new Scanner(System.in); c) The statement creates a Scanner and assigns the value to keyboard: keyboard = new Scanner(System.out); d) Programs that use a Scanner require an import statement be added to the class body. 1/29/2018 d) is false, the import is before the class header. A programmer needs to read a value that the user has entered to be treated as a number. One option is to read the data as: double number = keyboard.nextdouble(); The other option is to read the entire line the user enters. String data = keyboard.nextline(); How can the user convert this data to a double? a) Not possible. b) Use the statement: int val = Integer.parseDouble(); c) Use the statement: double val = Double.parseDouble(); d) Use the statement: double val = Double.parseDouble(data); 1/29/2018 d) is the only true statement. Notice that it is the only one that provides the data to the parse method. 9