COMP Introduction to Programming Primitive Types, Strings and Console I/O

Similar documents
Darrell Bethea May 25, 2011

COMP Introduction to Programming Midterm Review

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

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

Getting started with Java

Program Fundamentals

Computational Applications in Nuclear Astrophysics using Java Java course Lecture 2

CS 106 Introduction to Computer Science I

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

CSE20 : Lab #4 - Data Types

Programming with Java

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

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

Ex: If you use a program to record sales, you will want to remember data:

Full file at

Full file at

COMP Introduction to Programming If-Else Statement, Switch Statement and Loops

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

Lecture Set 2: Starting Java

CMPT 125: Lecture 3 Data and Expressions

Chapter 2: Data and Expressions

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Lecture Set 2: Starting Java

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

COMP 110 Introduction to Programming. What did we discuss?

Chapter 2: Data and Expressions

Program Elements -- Introduction

CIS 110: Introduction to Computer Programming

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

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

Object-Oriented Programming

Introduction To Java. Chapter 1. Origins of the Java Language. Origins of the Java Language. Objects and Methods. Origins of the Java Language

Chapter 3 Syntax, Errors, and Debugging. Fundamentals of Java

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

Chapter 2: Using Data

Data types Expressions Variables Assignment. COMP1400 Week 2

CS313D: ADVANCED PROGRAMMING LANGUAGE

Topic 4 Expressions and variables

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

AP Computer Science A

Arithmetic and IO. 25 August 2017

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

4. Inputting data or messages to a function is called passing data to the function.

Basic Computation. Chapter 2

COMP 202 Java in one week

Basics of Java Programming

Controls Structure for Repetition

Chapter 02: Using Data

COMP 110/L Lecture 4. Kyle Dewey

Computational Expression

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

Chapter 2: Data and Expressions

CEN 414 Java Programming

Peer Instruction 1. Elementary Programming

Building Java Programs

Static Imports, Default Values, Number Types and More!

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

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

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

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

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

DATA TYPES AND EXPRESSIONS

Visual C# Instructor s Manual Table of Contents

Chapter 2: Using Data

Introduction to Programming Using Java (98-388)

1007 Imperative Programming Part II

Midterms Save the Dates!

COMP 110 Introduction to Programming. What did we discuss?

Last Time. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings

Chapter 2: Using Data

IT 374 C# and Applications/ IT695 C# Data Structures

COMP 202. Java in one week

Course Outline. Introduction to java

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

Lecture 2: Variables & Assignments

Chapter 2 Elementary Programming

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

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

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

What did we talk about last time? Examples switch statements

Chapter. Let's explore some other fundamental programming concepts

2: Basics of Java Programming

Define a method vs. calling a method. Chapter Goals. Contents 1/21/13

C++ Basic Elements of COMPUTER PROGRAMMING. Special symbols include: Word symbols. Objectives. Programming. Symbols. Symbols.

CS11 Java. Fall Lecture 1

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

I Internal Examination Sept Class: - BCA I Subject: - Principles of Programming Lang. (BCA 104) MM: 40 Set: A Time: 1 ½ Hrs.

CPS122 Lecture: From Python to Java last revised January 4, Objectives:

Chapter 2 Primitive Data Types and Operations. Objectives

MODULE 02: BASIC COMPUTATION IN JAVA

Chapter 2 Part 2 Edited by JJ Shepherd, James O Reilly

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

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

Values, Variables, Types & Arithmetic Expressions. Agenda

Primitive Data, Variables, and Expressions; Simple Conditional Execution

AYBUKE BUYUKCAYLI KORAY OZUYAR MUSTAFA SOYLU. Week 21/02/ /02/2007 Lecture Notes: ASCII

First Java Program - Output to the Screen

CPS122 Lecture: From Python to Java

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

Transcription:

COMP 110-003 Introduction to Programming Primitive Types, Strings and Console I/O January 22, 2013 Haohan Li TR 11:00 12:15, SN 011 Spring 2013

Daily Joke Q: How did the programmer die in the shower? A: He read the shampoo bottle instructions: Lather, Rinse, Repeat.

Daily Joke Q: How did the programmer die in the shower? A: He read the shampoo bottle instructions: Lather, Rinse, Repeat. Use one word to tell: what is this in the world of a programmer?

Daily Joke Q: How did the programmer die in the shower? A: He read the shampoo bottle instructions: Lather, Rinse, Repeat. Use one word to tell: what is this in the world of a programmer? Algorithm: A set of instructions for solving a problem What s the problem with this algorithm?

Review Classes/Objects Attributes Methods Object-Oriented Programming/ Procedural Programming

SimCity 4 If we want to simulate such a city in computer What can be the Classes Objects Attributes Methods Start with class/object We ll brainstorm

Classes vs. Objects Classes: What we can create Objects: What have been created

Classes and Objects Classes House Market Power plant Hospital Objects? Those on the ground

More Classes More classes Road Rail Bridge

More Classes More Classes Tree Grass Animal Car People

More Class? Ground! Ground class can be big or small If it s big One object with many attributes If it s small Many objects with several attributes

Attributes? There can be a lot of them Name Style Area size Location etc.

Methods? Display() PutOnGround()

More Methods? AttractPeople() AffectEnviron() SupplyWater() SupplyPower() EarnMoney() PayTax() etc.

OOP vs Procedural Programming? Hard to perform simulation of a city using procedural programming We will use SimCity as an OOP example in future

Today Primitive Types and Expressions Strings Console I/O

Variables Used to store data in program The data currently in a variable is its value Name of variable is an identifier Can change value throughout program Choose variable names that are helpful amount, quarters, dimes, nickels

Variables and Memory A variable corresponds to a location in memory variable: amount Use this cell to store the value of total money amount main memory Prevent this cell from being used by other variables later

How to use variables Declare a variable Assign a value to the variable Change the value of the variable

Variable Declaration Syntax: type variable_1, variable_2, ; Examples: int count, score, myint; char letter; double totalcost, ratio;

How to name an identifier Naming rules: Letters, digits(0-9) First character cannot be a digit No spaces Java is case sensitive Legal names pinkfloyd, b3atles, eyecolor Illegal names michael.bolton, kenny-g, 1CP

Keywords Reserved words with predefined meanings You cannot name your variables keywords Inside cover of the textbook if, else, return, new

Type What kind of value the variable can hold Primitive type - indecomposable values Names usually begin with lowercase letters int, double, char, boolean See inside cover of the textbook Class type - objects with both data and methods Names usually begin with uppercase letter Scanner, String

Primitive Types Integer (byte, short, int, long) 0, -3, 5, 43 Floating-point number (float, double) 0.5, 12.4863, -4.3 Characters (char) A, r, %, T Boolean (boolean) true, false

Integer and Floating-Point Floating-point vs fixed-point 120000000000, 0.0000000000325 are fixed-point 1.2 x 10 11, 3.25 x 10-11 are floating-point In computer, you only have to save 12 and 11, or 325 and -11 Integer is an exact value Floating-point is an approximation value Consider: 1/3 = 0.33333333333333333333333 No way to save this exact number in finite memory

Variables and Memory When declaring a variable, a certain amount of memory is assigned/allocated based on the declared primitive type int age; double length; char letter; main memory What is this unit?

Assign and Change Variables int changingvar = 0; Declare and assign value type variable = value; changingvar = 5; Assign/change value, variable must be declared before variable = value; changingvar = changingvar + 4; Can refer to itself It means newvalue = oldvalue + 4. Now changingvar =?

Assignment Statements Change a variable s value Syntax: variable = expression; Example: sleepneeded = 8; sleepdesired = sleepneeded * 2;

Behind the Statement variable = expression; CPU calculates the value of the expression. Send the value to the location of variable. sleepdesired = sleepneeded * 2; Calculate sleepneeded * 2 Get the current value of sleepneeded from its memory location Assign the value to the location of sleepdesired

Special Assignment Operators Some operators are new to you total += 5; // is the same as total = total + 5; count++; // is the same as count = count + 1; They are created because It s shorter Less possibility of making mistakes

Assignment Compatibilities Usually, we need to put values of a certain type into variables of the same type. Put integer into int, floating-point into double, etc. However, in some cases, the value will automatically be converted when types are different int age= 10; double average = age;

Assignment Compatibilities You can only put small things into bigger things byte->short->int->long->float->double Some examples myshort = myint; Wrong mybyte = mylong; Wrong myfloat = mybyte; Right mylong = myint; Right

Type Casting You can ask the computer to change the type of values which are against the compatibility. myfloat = mydouble; mybyte = myint; myshort = myfloat; myfloat = (float)mydouble; mybyte = (byte)myint; myshort = (short)myfloat; It means you know the risk but you still want to change You may lose information

Arithmetic Operators Unary operators (more info later) +, -, ++, --,! Binary arithmetic operators *, /, %, +, - rate*rate + delta 1/(time + 3*mass) (a - 7)/(t + 9*v)

Modular Arithmetic - % Remainder 7 % 3 = 1 (7 / 3 = 2, remainder 1) 8 % 3 = 2 (8 / 3 = 2, remainder 2) 9 % 3 = 0 (9 / 3 = 3, remainder 0) clock arithmetic Minutes on a clock are mod 60

Parentheses and Precedence Expressions inside parentheses evaluated first (cost + tax) * discount cost + (tax * discount) Precedence order: First: the unary operators: ++, --,! Second: the binary arithmetic operators: *, /, % Third: the binary arithmetic operators: +, - In the same level, from left to right

Parentheses and Precedence These are the same: total = cost + tax * discount; total = cost + (tax * discount); The highest precedence level is marked in red Probably we wanted: total = (cost + tax) * discount; Full operator precedence table on back cover

Errors Syntax error grammatical mistake in your program int n3 = 10, // use a ; instead of a, Eclipse can only detect this level of error Run-time error an error that is detected during program execution int n3 = n1 / n2; // But n2 == 0 Logic error a mistake in a program caused by the underlying algorithm int n3 = n1 - n2; // But we meant to sum

Strings No primitive type for strings in Java Instead, Java provides a class called String Text is a value. You can declare String variables String month = May ; Similar to: int n1 = 10; System.out.println(month); month is a variable. Its value is May So it prints: May

String Concatenation We use + to connect multiple strings String month = May ; String sentence = This month is + month; System.out.println(sentence); It will print: This month is May Moreover, + can be used to connect String and other types int quarters = 3; System.out.println(quarters + " quarters");

String (Class type) Class types have methods Object String mystring = COMP110 ; int len = mystring.length(); len will be equal to 7 Method

Strings Methods (Figure 2.5) mystring.length(); mystring.equals( a string ); mystring.tolowercase(); mystring.trim(); You will see these in Lab 2

String Indices U N C i s G r e a t 0 1 2 3 4 5 6 7 8 9 10 11 String output = mystring.substring(1, 8); System.out.println(output); It will print: NC is G

String Indices U N C i s G r e a t 0 1 2 3 4 5 6 7 8 9 10 11 String output = mystring.substring(1, 8); System.out.println(output); It will print: NC is G WHY?

String Indices U N C i s G r e a t 0 1 2 3 4 5 6 7 8 9 10 11 It s easy to output a specified length. String output = mystring.substring(1, 8); System.out.println(output); It will print: NC is G WHY?

Put Quotes in a String What to do if you want to output How do I put quotes in my string? You will have trouble! System.out.println( How do I put quotes in my string? ); You have to let computer know that you want the quote marks to be in the String System.out.println( How do I put \ quotes\ in my string? );

But what about backslashes? Backslash in a String means: the next character is special System.out.println( How do I put a \\ in my string? ); It will print: How do I put a \ in my string?

Escape Characters \ Double quote \ Single quote \\ Backslash \n New line \t Tab

I/O (Input/Output) System.out.print( this is a string ); System.out.println( this is a string ); What is the difference? println() method advances to a new line after it displays its output, whereas the print() method does not Instead: System.out.print( this is a string\n );

Keyboard Input Use the Scanner class Scanner Scanner_object_name = new Scanner(System.in); Scanner_object_name.nextLine(); Scanner_object_name.nextInt(); Scanner_object_name.nextDouble(); Make sure to read Chapter 2.3, and the Gotcha before Figure 2.7

Program 1 No collaboration privilege You are allowed to Talk about textbook, notes and Java features Talk to understand the program requirement Let others see your program s problem only if You ve written a complete section of code but it s not working The one who helps has finished his/her own code The one who helps only tells you where the problem is and you will fix it all by yourself Key point: it must be your idea and your code If you get help on how to do something you don t have an idea, it s very easy to produce similar codes