Lecture 8: Bits and Pieces Tami Meredith. Roadmap Today's lecture has a bit of everything. Going back over previous chapters and pulling out little bits.

Slides:



Advertisements
Similar presentations
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
Advertisements

Aalborg Media Lab 21-Jun-15 Software Design Lecture 2 “ Data and Expressions”
Some basic I/O.
ECE122 L3: Expression Evaluation February 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 3 Expression Evaluation and Program Interaction.
Strings as objects Strings are objects. Each String is an instance of the class String They can be constructed thus: String s = new String("Hi mom!");
1 The First Step Learning objectives write Java programs that display text on the screen. distinguish between the eight built-in scalar types of Java;
Week 2 - Friday.  What did we talk about last time?  Data representation  Binary numbers  Types  int  boolean  double  char  String.
Expressions, Data Conversion, and Input
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Summary and Exam COMP 102.
Conditional If Week 3. Lecture outcomes Boolean operators – == (equal ) – OR (||) – AND (&&) If statements User input vs command line arguments.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Console Input & Output CSS 161: Fundamentals of Computing Joe McCarthy 1.
Math class services (functions) Primitive vs reference data types Scanner class Math class services (functions) Primitive vs reference data types Scanner.
A First Look at Java Chapter 2 1/29 & 2/2 Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
F27SA1 Software Development 1 3. Java Programming 2 Greg Michaelson.
College Board A.P. Computer Science A Topics Program Design - Read and understand a problem's description, purpose, and goals. Procedural Constructs.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Chapter 4: Control Structures II
OOP (pre) Basic Programming. Writing to Screen print will display the string to the screen, the following print statement will be appended to the previous.
Introduction to Programming
CMSC 202 Java Console I/O. July 25, Introduction Displaying text to the user and allowing the user to enter text are fundamental operations performed.
FUNDAMENTALS 2 CHAPTER 2. OPERATORS  Operators are special symbols used for:  mathematical functions  assignment statements  logical comparisons 
Zhen Jiang Dept. of Computer Science West Chester University West Chester, PA CSC141 Computer Science I 12/11/20151.
Lecture 2: 1226 Review Tami Meredith. Programming Process How do we fill in the yellow box? Text Editor Compiler (javac) Interpreter (JVM: java) User.
Lecture 9: Bits and Pieces, Part 2 Tami Meredith.
Lecture 12: Final Review Tami Meredith. Programming Requires 1. Identification of the problem Understanding it, identifying correct solutions 2. Solving.
CSC 1051 – Algorithms and Data Structures I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CS 106 Introduction to Computer Science I 02 / 01 / 2008 Instructor: Michael Eckmann.
Lecture 4: Looping Tami Meredith. Back to Basics... Programming requires: 1. Identification of the problem. 2. Solving the problem: A. Selecting the data.
By Mr. Muhammad Pervez Akhtar
Lecture 2: 1226 Review II Tami Meredith. Programming Process How do we fill in the yellow box? Text Editor Compiler (javac) Interpreter (JVM: java) User.
Lecture 10: Object Oriented Programming Tami Meredith.
Lecture 5: Methods Tami Meredith. Roadmap The new material this week is predominantly from Chapter 5 (and Section 6.2 on static ) You should try and read.
Midterm Review Tami Meredith. Primitive Data Types byte, short, int, long Values without a decimal point,..., -1, 0, 1, 2,... float, double Values with.
Keyboard and Screen I/O (Input/Output). Screen Output  System.out is an object that is part of the Java language. (Don’t worry yet about why there is.
Java Basics. Tokens: 1.Keywords int test12 = 10, i; int TEst12 = 20; Int keyword is used to declare integer variables All Key words are lower case java.
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
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.
Java I/O Basics MIS 3023 Business Programming Concepts II The University of Tulsa Professor: Akhilesh Bajaj All slides in this presentation ©Akhilesh Bajaj,
Fundamentals 2 1. Programs and Data Most programs require the temporary storage of data. The data to be processed is stored in a temporary storage in.
OPERATORS IN C CHAPTER 3. Expressions can be built up from literals, variables and operators. The operators define how the variables and literals in the.
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.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Lecture 4 CS140 Dick Steflik. Reading Keyboard Input Import java.util.Scanner – A simple text scanner which can parse primitive types and strings using.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CompSci 230 S Programming Techniques
BIT 115: Introduction To Programming
Lecture 2 D&D Chapter 2 & Intro to Eclipse IDE Date.
BIT 115: Introduction To Programming
Chapter 2 More on Math More on Input
Crash course in the Java Programming Language
Building Java Programs
Introduction to Computer Science / Procedural – 67130
CSC 1051 – Data Structures and Algorithms I
Data Conversion & Scanner Class
BIT115: Introduction to Programming
Program Style Console Input and Output
CSS 161 Fundamentals of Computing Introduction to Computers & Java
Introduction to Classes and Methods
Building Java Programs
Fundamentals 2.
Building Java Programs
Unit 3: Variables in Java
CSS161: Fundamentals of Computing
Building Java Programs
Presentation transcript:

Lecture 8: Bits and Pieces Tami Meredith

Roadmap Today's lecture has a bit of everything. Going back over previous chapters and pulling out little bits I haven't covered yet or did not cover in much depth Providing gentle introductions to things you don't really need to know, but that you should be aware that they exist Lots and lots of exercises

Methods Buildings are too big to be designed in a single drawing Architects design houses in parts – a basement floor plan, a first floor plan, an exterior (lot) plan, and so on... Programs are also too big to be designed as a single part We break programs into parts – these parts are called methods A method is PART of a program – it will not execute/run by itself Methods need data to work: Input – from other parts of the program, via parameters Output – to other parts of the program, via the return value

A Method public static boolean isEven (int val) { if ((val % 2) == 0) { return (true); } else { return (false); } Input: val, of type int Output (return value): a boolean This method is only part of a program, it won't work by itself A named block of code, the block is called isEven

Exercise Write a method that takes two strings and returns (as a new string) the longest common prefix of both strings E.g., the longest prefix of "Money" and "Motion" is "Mo" The method should be case sensitive

Solution // Note: Fails if si is a prefix of sj public static String lcp (String s1, String s2) { int i = 0; while (s1.charAt(i) == s2.charAt(i)) { i++; } return (s1.substring(0,i)); }

Variable Modification We can modify variables in several ways: 1. Assignment: x = 7; y = 3 * x; 2. Increment/Decrement: x++; --y; 3. Combined assignment and an operation: x += 1; This is called compound assignment. The compound operators are: +=, -=, *=, /=, %= (there are more, &=, <<=, etc.) x += 1; is the same as x = x + 1; y *= x; is the same as y = y * x;

Increment/Decrement (Review) ExpressionAlternative i++;i = i + 1; ++i;i = i + 1; i--;i = i – 1; --i;i = i – 1; j = i++;j = i; i = i + 1; j = ++i;i = i + 1; j = i; j = i--;j = i; i = i - 1; j = --i;i = i – 1; j = i;

Incrementing X There are a lot of ways to increment a variable: 1. x++; 2. ++x; 3. x = x + 1; 4. x += 1; It is only when ++ is used in another expression that its location (before or after the variable) becomes important in this example it does not matter and all four expressions are identical

Expressions vs. Statements Expressions generate a value that can be used in an assignment can also be used as function arguments e.g., 3+4, x-y, max(a,b), data.length Statements perform an action but do not generate a value e.g., while (true) {... }, println();

Conditional Expressions An expression with a condition Generate a value, can be used in assignments Format: (test) ? true-value : false-value Examples diff = (x > y) ? x-y : y-x; max = (x > y) ? x : y; mean = (n == 0) ? 0 : sum/n;

Syntactic Sugar The statement mean = (n == 0) ? 0 : sum/n; Is really just a compact way of saying if (n == 0) mean = 0; else mean = sum/n; The term syntactic sugar is used to refer to optional (not really needed) constructs that make code "sweeter" to read Compound assignment is another example of syntactic sugar, e.g., x += 7; is the same as x = x + 7;

Precedence There is a complex precedence (order of operations) for Java's operators DON'T rely on it, DON'T waste a lot of effort memorising it INSTEAD – use parentheses (i.e., ' ( ' and ' ) ') liberally to make things happen in the order that you want Parentheses also make things much clearer as well as avoiding surprise/errors due to precedence

See: Text Fig 3.9

Shifts It is possible to work with the individual bits of a value This is an advanced technique that is used to create more efficient code (save time or space) We will not be doing any shifts, but you should know that they exist byte x = 9; // x = ; x = x << 2; // x = ; x = x >> 1; // x = ;

Bitwise Operations Like shifts, bitwise operations work on the specific bits of a value They are another advanced tool that you won't need in this course, but are useful to be aware of NOTE: & is not the same as &&, will generate different results | is not the same as ||, will generate different results ^ is an operator Knowing they are here and different will help you find and hopefully avoid mistakes

Keyboard Input (Review) It is useful to get input from the user Until now we have provided the code to do this for you System.in is an object of type InputStream It is not very useful since you can only read bytes from an InputStream We apply a Scanner to the InputStream to 1. Break the stream into meaningful parts (e.g., integers, lines, words) 2. Change the parts into useful types (e.g., ints, floats, Strings )

Useful Methods See Figure 2.7 (Page 98) of the text next(), gets the next word nextLine(), gets the next line, discards the newline nextInt(), gets the next integer hasNextLine(), checks if there is another line, returns a boolean hasNextInt(), checks if there is another int, returns a boolean There are many other methods you can use, see: You need to know the delimiter – what ends a word, an integer, etc.

Example (Code Fragments) import java.util.Scanner; // import java.util.*; Scanner scn= new Scanner(System.in); String line; if (scn.hasNextLine()) { line = scn.nextline(); }

Exercise Write a program that asks the user for a pair of integers and prints all the even numbers (in increasing order) between the two integers The output should be on one line and separated by commas Example: Enter the first number: 11 Enter the second number: 4 4, 6, 8, 10

Solution import java.util.Scanner; public class evens { public static void main (String[] args) { Scanner keyboard = new Scanner (System.in); System.out.print("Enter the first integer: "); int i1 = keyboard.nextInt(); System.out.print("Enter the second integer: "); int i2 = keyboard.nextInt(); int start = (i1 < i2) ? i1 : i2; start = ((start % 2) == 0) ? start : start + 1; int end = (i2 > i1) ? i2 : i1; end = ((end % 2) == 0) ? end : end – 1; for (int i = start; i <= end; i += 2) { System.out.print(i); if (i != end) System.out.print(", "); } System.out.println(""); } // end main() } // end class evens

Wrapper Classes Every primitive type has a class E.g., int s are associated with Integer The class can be used when we need to treat the int as a class The class also has a set of useful static methods we can call to manipulate integers for us e.g., Integer.parseInt(String) converts a String into an int See: Figure 2.9 (page 123) provides other methods for converting Strings into primitive types Wrapper classes are not important to learn at this point...

Example (Code Fragments) import java.util.*; Scanner keyboard = new Scanner(System.in); String number = keyboard.next(); /* There is a way to identify when the * conversion fails so we can try * something else */ int n = Integer.parseInt(number);

Short-Circuit Evaluation Recall: x && y is true when both x and y are true If x is false, it really doesn't matter what y is – the expression can never be true To save time, y is never examined if x is false! This behaviour is called short circuit evaluation We can use this to our benefit... if (keyboard.hasNext() && (word = keyboard.next())) { System.out.println("Read: " + word); }

More Short Circuitry Recall: x || y is true if x is true or y is true If x is true, it doesn't really matter what y is since the expression will always evaluate to true To save effort, we never examine y if x is true Example if ((s.length() > 0) || (s = "Empty")) { System.out.println("String is: " + s); }

ASCII Every character has a value We store the value, not the character We can treat characters as numbers as a consequence The values assigned are based on the ASCII encoding 0-127: Basic ASCII : Extended ASCII : Unicode (subsumes ASCII)

Hexidecimal Our ASCII table had "hex" values Hexidecimal is base 16 Digits are 0, 1,..., 0, A, B, C, D, E, F (lower case is OK) Hex is used a lot by programmers because 16 is a power of 2 and can be represented by 4 bits Again, you don't need to know it, but being aware that it exists is useful Prefix hex constants with 0x int x = 0x10; // x = hexidecimal 10 = 16;

Exercise Write a program that prints out the letters of the alphabet in the following format: A, a B, b C, c... Z, z Note, you don't need hexidecimal for this (or any) exercise, I mentioned it so you'd know what Hex meant in the ASCII table

Solution public class alphabet { public static void main (String[] args) { char lower = 'a', upper = 'A'; do { System.out.println( upper++ + ", " + lower++); } while (upper <= 'Z'); } // end main() } // end class alphabet

Solution (alternative) public class alphabet { public static void main (String args) { char lower = 'a', upper = 'A'; for (; upper <= 'Z'; upper++, lower++) { System.out.println(upper + ", " + lower); } } // end main() } // end class alphabet

Exercise Write a program that asks a user for an integer from 1 to 26 and then prints out the equivalent letter of the alphabet (e.g., 'a' for 1, 'b' for 2) E.g., Enter an integer: 10 Character 10 is j

Solution public class letters { public static void main (String[] args) { Scanner keyboard = new Scanner (System.in); int input; char c; System.out.print("Enter an integer: "); i = keyboard.nextInt(); if ((i 26)) { System.out.println("Value was not in range (1..26)"); } else { c = (char) (i + '`'); // c = (char) (i + 96); System.out.println("Character " + i + " is " + c); } } // end main(() } // end class letters

Keep Going! We're getting there

To Do Go to the lab and complete Assignment 7 Read and re-read Chapters 1-4, and 7 – know this material VERY well Keep working on Chapters 5, 6 - most of Chapter 6 we have not covered, nor the part of Chapter 5 on objects and classes Practice, Practice, Practice