Week 4 - Friday CS 121.

Slides:



Advertisements
Similar presentations
Escape Sequences \n newline \t tab \b backspace \r carriage return
Advertisements

CS0007: Introduction to Computer Programming Console Output, Variables, Literals, and Introduction to Type.
Introduction to Computing Concepts Note Set 7. Overview Variables Data Types Basic Arithmetic Expressions ▫ Arithmetic.
 2005 Pearson Education, Inc. All rights reserved Introduction.
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
Week 1 - Wednesday.  What did we talk about last time?  Syllabus  Computers.
Week 2: Primitive Data Types 1.  Programming in Java  Everything goes inside a class  The main() method is the starting point for executing instructions.
10-Jun-15 Introduction to Primitives. 2 Overview Today we will discuss: The eight primitive types, especially int and double Declaring the types of variables.
©2004 Brooks/Cole Chapter 2 Variables, Values and Operations.
Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types.
CMT Programming Software Applications
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
COMP 14: Intro. to Intro. to Programming May 23, 2000 Nick Vallidis.
COMP 14: Primitive Data and Objects May 24, 2000 Nick Vallidis.
Week 2 - Friday.  What did we talk about last time?  Data representation  Binary numbers  Types  int  boolean  double  char  String.
© The McGraw-Hill Companies, 2006 Chapter 1 The first step.
COMP 110: Introduction to Programming Tyler Johnson January 14, 2009 MWF 11:00AM-12:15PM Sitterson 014.
Week 2 - Monday.  What did we talk about last time?  Software development  Lab 1.
Week 3 - Wednesday.  What did we talk about last time?  Math methods  Lab 2.
Introduction to Computer Systems and the Java Programming Language.
Week 1 - Friday.  What did we talk about last time?  Our first Java program.
Week 2 - Wednesday.  What did we talk about last time?  Data representation  Binary numbers  Types  int  boolean  double  char  String.
Week 2 - Friday.  What did we talk about last time?  Using Scanner to get input  Basic math operations.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
Introduction to Java Java Translation Program Structure
Week 15 - Monday.  What did we talk about last time?  File I/O.
Operators and Expressions. 2 String Concatenation  The plus operator (+) is also used for arithmetic addition  The function that the + operator performs.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 2A Reading, Processing and Displaying Data (Concepts)
CHAPTER 2 PROBLEM SOLVING USING C++ 1 C++ Programming PEG200/Saidatul Rahah.
CS 106 Introduction to Computer Science I 09 / 10 / 2007 Instructor: Michael Eckmann.
Chapter 2: Data and Expressions. Variable Declaration In Java when you declare a variable, you must also declare the type of information it will hold.
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
Week 4 - Friday.  What did we talk about last time?  Examples  switch statements.
Week 3 - Monday.  What did we talk about last time?  Using Scanner to get input  Basic math operations  Lab 2.
Lecture 4 – Scanner & Style
Week 1 - Wednesday CS 121.
Information and Computer Sciences University of Hawaii, Manoa
Week 2 - Wednesday CS 121.
Chapter 2 Variables.
Week 3 - Wednesday CS 121.
Topics Designing a Program Input, Processing, and Output
Chapter 2 Basic Computation
BASIC ELEMENTS OF A COMPUTER PROGRAM
Week 3 - Friday CS222.
Console Output, Variables, Literals, and Introduction to Type
Variables and Primative Types
Fundamental of Java Programming Basics of Java Programming
Java Programming: From Problem Analysis to Program Design, 4e
Week 3: Basic Operations
Chapter 2 Basic Computation
CS 177 Week 3 Recitation Slides
Introduction to C++ Programming
Introduction to Java, and DrJava part 1
Review for Exam 1 Spring 2007 CS 101/CS 101-E.
Elementary Programming (C++)
Focus of the Course Object-Oriented Software Development
Topics Designing a Program Input, Processing, and Output
Topics Designing a Program Input, Processing, and Output
Introduction to Primitives
Fundamental OOP Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
Introduction to Primitives
In this class, we will cover:
Unit 3: Variables in Java
Chapter 2 Variables.
The Study of Computer Science Chapter 0
Week 1 - Friday COMP 1600.
Presentation transcript:

Week 4 - Friday CS 121

Last time What did we talk about last time? Examples switch statements

Questions?

Project 1

Review

Week 1 review topics History of computers Hardware Software development Basic Java syntax Output with System.out.print()

History of computers Mechanical Calculation Devices (2400BC onward) Aid to human calculation No stored program Mechanical Computers (1725 onward) Punch card programming Serious limitations Early Electronic Computers (1941 onward) General purpose, stored program computers Electronic, using vacuum tubes Microprocessors (1970's onward) Succeeded transistors Now billions of computations per second at a nanometer scale

Memory Cache RAM Flash Drive Hard Drive Optical Drive Actually on the CPU Fast and expensive RAM Primary memory for a desktop computer Pretty fast and relatively expensive Flash Drive Faster than hard drives Seen on USB drives but SSDs are becoming common too Hard Drive Secondary memory for a desktop computer Slow and cheap Optical Drive Secondary memory that can usually only be written once Very slow and very cheap

Memory Storage for all the data and instructions on your computer Modern computers store everything as binary digits (bits) which have a value of 0 or 1. 1 byte = 8 bits 1 kilobyte (kb) = 210 bytes 1 megabyte (mb) = 220 bytes 1 gigabyte (gb) = 230 bytes 1 terabyte (tb) = 240 bytes

Input/Output Monitor Speakers Mouse Keyboard Common visual output device Speakers Common audio output device Mouse Common input device Keyboard

General compilation model Solve a problem; Computer! 001110010 010100101 010101010 Source Code Machine Code Hardware

Compilation and Execution for Java } p.solve(); Problem p; { class A 110010011 101011010 101110101 001110010 010100101 010101010 Java Source Code Java Bytecode Machine Code Hardware Platform Independent Platform Dependent

Software development Often goes through phases similar to the following: Understand the problem Plan a solution to the problem Implement the solution in a programming language Test the solution Maintain the solution and do bug fixes Factor of 10 rule!

A basic Java program The absolute smallest program possible, with a print statement public class Hello { public static void main(String[] args) System.out.println("Hello, world!"); }

Sequencing For example, instead of one print statement, we can have several: Each statement is an instruction to the computer They are printed in order, one by one System.out.println("Hello, world!"); System.out.println("Hello, galaxy!"); System.out.println("Goodbye, world!");

Case Sensitivity Java is a case sensitive language Class is not the same as class System.out.println("Word!"); prints correctly system.Out.Println("Word!"); does not compile

Whitespace Java generally ignores whitespace (tabs, newlines, and spaces) is the same as: You should use whitespace effectively to make your code readable System.out.println("Hello, world!"); System.out. println( "Hello, world!");

Comments There are two kinds of comments (actually 3) Single line comments use // Multi-line comments start with a /* and end with a */ System.out.println("Hi!"); // this is a comment System.out.println("Hi!"); /* this is a multi-line comment */

Week 2 review topics Binary representation Basic data types Using Scanner for input

Base 2 (binary) numbers The binary number system is base 2 This means that its digits are: 0 and 1 Base 2 means that you need 2 digits to represent two, namely 1 and 0 Each place in the number as you move left corresponds to an increase by a factor of 2 instead of 10

11111100001 Base 2 Example Sixty fours 256’s Sixteens Fours 1024’s Ones 512’s 128’s Thirty twos Eights Twos

Built-in types We're focusing on five basic types of data in Java These are: int For whole numbers double For rational numbers boolean For true or false values char For single characters String For words String is a little different from the rest, since you can call methods on it (and for other reasons)

Summary of types Type Kind of values Sample Literals int double Integers -5 900031 double Floating-point Numbers 3.14 -0.6 6.02e23 boolean Boolean values true false char Single characters 'A' 'Z' '&' String Sequences of characters "If you dis Dr. Dre" "10 Sesquipedalians"

The int type The int type is used to store integers (positive and negative whole numbers and zero) Examples: 54 -893992 Inside the computer, an int takes up 4 bytes of space, which is 32 bits (1's and 0's)

The double type You will use the int type very often Sometimes, however, you need to represent numbers with a fractional part The double type is well suited to this purpose Declaration of a double variable is just like an int variable: double x;

The boolean type Numbers are great But, sometimes you only need to keep track of whether or not something is true or false This is what the boolean type is for Hopefully you have more appreciation for booleans now Declaration of a boolean variable is like so: boolean value;

The char type Sometimes you need to deal with characters This is what the char type is for The char type only allows you to store a single character like '$' or 'q' Declaration of a char variable is like so: char c;

The String type The String type is different from the other types in several ways The important thing for you to focus on now is that it can hold a large number of chars, not just a single value A String literal is what we used in the Hello, World program String word;

Using Scanner There are three parts to using Scanner for input Include the appropriate import statement so that your program knows what a Scanner object is Create a specific Scanner object with a name you choose Use the object you create to read in data

Importing Scanner Lots of people have written all kinds of useful Java code By importing that code, we can use it to help solve our problems To import code, you type import and then the name of the package or class To import Scanner, type the following at the top of your program (before the class!) import java.util.Scanner;

Creating a Scanner object Once you have imported the Scanner class, you have to create a Scanner object To do so, declare a reference of type Scanner, and use the new keyword to create a new Scanner with System.in as a parameter like so: You can call it whatever you want, I chose to call it in Doesn't make any sense? For now, that's okay. Scanner in = new Scanner(System.in);

Using a Scanner object Now that you've got a Scanner object, you can use it to read some data It has a method that will read in the next piece of data that user types in, but you have to know if that data is going to be an int, a double, or a String Let's say the user is going to input her age (an int) and you want to store it in an int variable called years We'll use the nextInt() method to do so: int years; years = in.nextInt();

Scanner methods Scanner has a lot of methods (ways to accomplish some tasks) For now, we're only interested in three These allow us to read the next int, the next double, and the next String, respectively: Scanner in = new Scanner(System.in); int number = in.nextInt(); double radius = in.nextDouble(); String word = in.next();

Week 3 review topics Numerical operations Advanced math operations boolean operations char operations String operations Wrapper classes

Numerical operations + adds - subtracts * multiplies / divides (integer division for int type and fractional parts for double type) % finds the remainder

Complex expressions Order of operations holds like in math You can use parentheses to clarify or change the precedence Now a is 16 int a = 31; int b = 16; int c = 1; int d = 2; a = (((b + c) * d) – a / b) / d;

Casting You cannot directly store a double value into an int variable However, you can cast the double value to convert it into an int Casting tells the compiler that you want the loss of precision to happen You can always store an int into a double int a = 2.6; // fails! int a = (int)2.6; // succeeds! (a = 2)

Math method example with sin() The sin() method allows you to find the sine of an angle (in radians) This method is inside the Math class The answer that it gives back is of type double To use it, you might type the following: double value = Math.sin( 2.4 );

Rounding In Java, the conversion of a double into an int does not use rounding As in the case of integer division, the fractional part is dropped For positive numbers, that's like using floor For negative numbers, that's like using ceiling The right way to do rounding is to call Math.round() double x = 2.6; int a = (int)Math.round(x); // rounds

Math methods Return type Name Job double sin( double theta ) Find the sine of angle theta cos( double theta ) Find the cosine of angle theta tan( double theta ) Find the tangent of angle theta exp( double a ) Raise e to the power of a (ea) log( double a ) Find the natural log of a pow( double a, double b ) Raise a to the power of b (ab) long round( double a ) Round a to the nearest integer random() Create a random number in [0, 1) sqrt( double a ) Find the square root of a toDegrees( double radians ) Convert radians to degrees toRadians( double degrees ) Convert degrees to radians

boolean operations ! NOT && AND || OR ^ XOR Flips value of operand from true to false or vice versa && AND true if both operands are true || OR true if either operand is true ^ XOR true if operands are different

Short circuit evaluation In some circumstances, Java doesn't check the whole expression: (true || (some complicated expression)) Ignores everything after || and gives back true (false && (some complicated expression)) Ignores everything after && and gives back false

char operations char values can be treated like an int It can be more useful to get the offset from a starting point int number; number = 'a'; // number contains 97 char letter = 'r'; int number; number = letter – 'a' + 1; //number is 18

Escape sequences Remember that we use single quotes to designate a char literal: 'z' What if you want to use the apostrophe character ( ' )? apostrophe: '\'' What if you want to use characters that can't be printed, like tab or newline? tab: '\t' newline: '\n' The backslash is a message that a special command called an escape sequence is coming These can be used in String literals as well: "\t\t\t\nThey said, \"Wow!\""

String concatenation The only operator that we will use directly with Strings is the + (concatenation) operator This operator creates a new String that is the concatenation of the two source Strings Concatenation can be used to insert the values of other types into Strings as well String word; word = "tick" + "tock"; // word is "ticktock"

String methods equals() compareTo() length() charAt() substring() Tests two Strings to see if they are the same compareTo() Returns a negative number if the first String comes earlier in the alphabet, a positive number if the first String comes later in the alphabet, and 0 if they are the same length() Returns the length of the String charAt() Returns the character at a particular index inside the String substring() Returns a new String made up of the characters that start at the first index and go up to but do not include the second index

Wrapper classes Each primitive data type in Java has a wrapper class Integer Allows String representations of integer values to be converted into ints Double Allows String representations of floating point values to be converted into doubles Character Provides methods to test if a char value is a digit, is a letter, is lower case, is upper case Provides methods to change a char value to upper case or lower case

Week 4 review topics Making choices with if statements Basics Having if bodies with more than one line Using else blocks Nesting if statements Using switch statements

if( condition ) statement; Anatomy of an if Any boolean expression The if part if( condition ) statement; Any single executable statement

Two different outcomes Anatomy of an if-else if( condition ) statement1; else statement2; Two different outcomes

An if with multiple statements if( condition ) { statement1; statement2; … statementn; } A whole bunch of statements

Nested ifs if( condition1 ) { statement1; if( condition2 ) … }

Comparison The most common condition you will find in an if is a comparison between two primitive types In Java, that comparison can be: == equals != does not equal < less than <= less than or equal to > greater than >= greater than or equal to

Anatomy of a switch statement switch( data ) { case value1: statements 1; case value2: statements 2; … case valuen: statements n; default: default statements; }

Peculiarities of switch Both "Three" and "Four" are printed int data = 3; switch( data ) { case 3: System.out.println("Three"); case 4: System.out.println("Four"); break; case 5: System.out.println("Five"); } Go to SwitchAge The break is optional The default is optional too

Rules for switch The data that you are performing your switch on must be either an int, a char, or a String The value for each case must be a literal Execution will jump to the case that matches If no case matches, it will go to default If there is no default, it will skip the whole switch block Execution will continue until it hits a break

Lab 4

Upcoming

Next time… Exam 1

Reminders Study for Exam 1 Keep working on Project 1, due tonight by 11:59! Never look at another student's code