CSCI 51 Introduction to Computer Science Dr. Joshua Stough January 29, 2009.

Slides:



Advertisements
Similar presentations
 2005 Pearson Education, Inc. All rights reserved Introduction.
Advertisements

1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
CMT Programming Software Applications
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 28, 2005.
Aalborg Media Lab 21-Jun-15 Software Design Lecture 2 “ Data and Expressions”
COMP 110 Introduction to Programming Mr. Joshua Stough September 5, 2007.
Program Elements We can now examine the core elements of programming (as implemented in Java) We focuse on: data types variable declaration and use, constants.
ECE122 L3: Expression Evaluation February 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 3 Expression Evaluation and Program Interaction.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
COMP 14 Introduction to Programming Miguel A. Otaduy May 14, 2004.
COMP 110 Introduction to Programming Mr. Joshua Stough September 10, 2007.
CSci 142 Data and Expressions. 2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data.
String Escape Sequences
© The McGraw-Hill Companies, 2006 Chapter 1 The first step.
Expressions, Data Conversion, and Input
1 2 2 Introduction to Java Applications Introduction Java application programming –Display messages –Obtain information from the user –Arithmetic.
Android How to Program, 2/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Primitive Types, Strings, and Console I/O Chapter 2.1 Variables and Values Declaration of Variables Primitive Types Assignment Statement Arithmetic Operators.
COMP 110 Introduction to Programming Mr. Joshua Stough August 29, 2007 Monday/Wednesday/Friday 3:00-4:15 Gardner Hall 307.
Chapter 2 Basic Elements of Java. Chapter Objectives Become familiar with the basic components of a Java program, including methods, special symbols,
Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Input, Output, and Processing
CIS 260: App Dev I. 2 Programs and Programming n Program  A sequence of steps designed to accomplish a task n Program design  A detailed _____ for implementing.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Week 1 Algorithmization and Programming Languages.
Copyright © 2012 Pearson Education, Inc. Chapter 2: Introduction to C++
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
CIS 260: App Dev I. 2 Programs and Programming n Program  A sequence of steps designed to accomplish a task n Program design  A detailed _____ for implementing.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Java Programming: From Problem Analysis to Program Design, 5e Chapter 2 Basic Elements of Java.
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.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
1 Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
© 2004 Pearson Addison-Wesley. All rights reserved ComS 207: Programming I Instructor: Alexander Stoytchev
FUNDAMENTALS 2 CHAPTER 2. OPERATORS  Operators are special symbols used for:  mathematical functions  assignment statements  logical comparisons 
Chapter 2 Variables.
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
Programming in Java (COP 2250) Lecture 4 Chengyong Yang Fall, 2005.
Operators and Expressions. 2 String Concatenation  The plus operator (+) is also used for arithmetic addition  The function that the + operator performs.
CSC 1051 – Algorithms and Data Structures I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CSCI 51 Introduction to Programming Dr. Joshua Stough January 27, 2009.
CSCI 51 Introduction to Computer Science Joshua Stough February 3, 2009.
CHAPTER 2 PROBLEM SOLVING USING C++ 1 C++ Programming PEG200/Saidatul Rahah.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
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.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
COMP 14 Introduction to Programming Mr. Joshua Stough January 24, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.
Data and Expressions. Let's explore some other fundamental programming concepts Chapter 2 focuses on: Character Strings Primitive Data The Declaration.
© 2004 Pearson Addison-Wesley. All rights reserved August 27, 2007 Primitive Data Types ComS 207: Programming I (in Java) Iowa State University, FALL 2007.
Java Programming: Guided Learning with Early Objects Chapter 1 Basic Elements of Java.
Chapter 2 Introduction to C++ Programming
Introduction to Computer Science / Procedural – 67130
Yanal Alahmad Java Workshop Yanal Alahmad
Primitive Data Types August 28, 2006 ComS 207: Programming I (in Java)
Data Conversion & Scanner Class
Multiple variables can be created in one declaration
Java Programming: From Problem Analysis to Program Design, 4e
Introduction to C++ Programming
Chapter 2 Edited by JJ Shepherd
Chapter 2: Basic Elements of Java
MSIS 655 Advanced Business Applications Programming
Focus of the Course Object-Oriented Software Development
Introduction to Java Applications
Unit 3: Variables in Java
Presentation transcript:

CSCI 51 Introduction to Computer Science Dr. Joshua Stough January 29, 2009

Announcements Problem Set 1 due Monday 11:59pm Submit through Sakai Assignments Assignments Assignments

Review Identifiers –can be composed of any combination of letters, digits, underscore (_), and dollar sign ($) –cannot begin with a digit –Java is case-sensitive Data Types –main integer type: int –main floating-point type: double –others: char, boolean

Arithmetic Operators: If one of the operands is floating-point, the result is a floating-point Casting –(int) (54.9) - truncates the floating-point number –(int) (a +.5) - rounds to nearest integer –(int) (a + 1) - rounds up to integer –(double) (23) - adds a.0 to the integer addition+ subtraction- multiplication* division/ remainder (mod)% Review

Review Questions 1. If you go to Best Buy and the salesperson tells you that they have a new Intel® Core™2 Extreme QX6700 (8MB,3.46GHz Factory overclocked) with 4 GB RAM and a 320 GB Performance RAID 0 drive, what does this mean? 2. 3 % % % CPU: Intel processor with 8 MB L2 cache, running at 3.46 GHz main memory: 4 GB secondary storage: 320 GB

Algorithm Design Example Problem: Convert change in cents to number of half- dollars, quarters, dimes, nickels, and pennies to be returned. Example: –given 646 cents –number of half-dollars: divide 646 by 50 quotient is 12 (number of half-dollars) remainder is 46 (change left over) –number of quarters: divide 46 by 25 quotient is 1 (number of quarters) remainder is 21 (change left over) –number of dimes, nickels, pennies –result: 12 half-dollars, 1 quarter, 2 dimes, 0 nickels, 1 penny

Resulting Algorithm 1. Get the change in cents 2. Find the number of half-dollars 3. Calculate the remaining change 4. Find the number of quarters 5. Calculate the remaining change 6. Find the number of dimes 7. Calculate the remaining change 8. Find the number of nickels 9. Calculate the remaining change 10. The remaining change is the number of pennies.

Review Problem Solving Steps: –understand the problem how would you solve the problem (as a human, without a computer) –dissect the problem into manageable pieces –design a solution –consider alternatives to the solution and refine it –implement the solution –test the solution and fix any problems that exist

Today- quick reminders from last time. Constants Variables Assignment Reading keyboard input String concatenation

Today – new stuff Increment/Decrement (new) Program Structure –Comments –Main, static, etc. –Import –Pre-defined classes and methods –Style and whitespace

Storing Data in Memory 1.Instruct the computer to allocate memory (declaration) how much? based on data type how to access? name the memory location 2.Include statements in the program to put data into the allocated memory assign a particular value to a particular memory location initialization - putting the first (initial) value into the memory location—the first assignment

Types of Storage Named Constant –once the value is stored in memory, it can't be changed Variable –the value stored in memory can be changed (can vary)

Named Constant static final dataType IDENTIFIER = value; Declared by using the reserved word final Always initialized when it is declared Style: Identifier should be in ALL CAPS, separate words with underscore (_) Example: –1 inch is always 2.54 centimeters final double CM_PER_INCH = 2.54;

Variable dataType identifier; Must be declared before it can be used Can be (but doesn't have to be) initialized when declared Identifier should start in lowercase, indicate separate words with uppercase Example: –number of students in class int numStudents; Multiple variables (of the same data type) can be declared on a single line int numStudents, numGrades, total;

Variable A variable can be given an initial value in the declaration When a variable is referenced in a program, its current value is used int total = 16; int base = 32, max = 149; total

Naming Variables Variables should be descriptively named We should be able to tell what type of information the variable holds by its name Remember Java is case-sensitive!

Assignment variable = expresssion; Assignment Operator (=) expression can be a value (3) or a mathematical expression (2 + 1), or… The expression must evaluate to the same data type as the variable was declared

total = 54+1; total Assignment assignment statement –changes the value of a variable Expression on right is evaluated and result is stored in variable on the left Value that was in total is overwritten 16 55

Assignment The assignment operator has a lower precedence than the arithmetic operators First the expression on the right hand side of the = operator is evaluated Then the result is stored in the variable on the left hand side answer = sum / 4 + MAX * lowest;

Assignment The right and left hand sides of an assignment statement can contain the same variable First, one is added to the original value of count Then the result is stored back into count (overwriting the original value) count = count + 1;

Questions What is stored in the memory location referred to by the identifier num after each of the following statements is executed in order? int num; num = 3; num = ; num = num * 2; num = ; nothing would give an error since would not result in an int

Questions Write Java statements to accomplish the following: 1. Declare int variables x and y 2. Update the value of an int variable x by adding 5 to it 3. Declare and initialize an int variable x to 10 and a char variable ch to 'B' 4. Declare int variables to store four integers int x, y; x = x + 5; int x = 10; char ch = 'B'; int num1, num2, num3, num4;

The Value of Variables We can use variables to save the result of expressions for use later in our programs. int sum, count; double average; sum = ; count = 3; average = (double) sum / count;

Questions Which of the following are valid Java assignment statements? Assume that i, x, and percent have been declared as double variables and properly initialized. 1.i = i + 5; 2.x + 2 = x; 3.x = 2.5 * x; 4.percent = 10% valid invalid valid invalid

Reading Keyboard Input We can let the user assign values to variables through keyboard input Java input is accomplished using objects that represent streams of data A stream is an ordered sequence of bytes The System.in object represents a standard input stream, which defaults to the keyboard

Reading Keyboard Input import java.util.Scanner;... Scanner scan = new Scanner(System.in); int a = scan.nextInt(); double d = scan.nextDouble(); String s = scan.nextString(); String s = scan.next(); //for a token. String s = scan.nextLine();

String to Numbers String to int Integer.parseInt(strExpression) Integer.parseInt("6723")6723 String to float Float.parseFloat(strExpression) Float.parseFloat("345.76") String to double Double.parseDouble(strExpression) Double.parseDouble(" ")

Initializing Variables Initialize - give a variable some initial value Must initialize variables before using them (e.g., before they appear on the right-hand side of an assignment statement) Two ways to initialize variables: 1. assignment statement feet = 35; 2. user input create Scanner object scan ask user for input feet = Integer.parseInt (scan.next()); or feet = scan.nextInt();

Questions What is stored in the variables numStudents and line after the following statements have been executed? (Assume that scan is a Scanner object). int numStudents; String line; // user asked for # of students // user enters 140 line = scan.nextLine(); numStudents = Integer.parseInt(line); numStudentsline nothing n/a nothing “140” nothing “140” 140

More Operators Increment and Decrement Increment (++) –adds 1 to any integer or floating point count++; count = count + 1; Decrement (--) –subtracts 1 from any integer or floating point count--; count = count - 1;

Increment and Decrement Prefix( ++count or --count ) –value used in a larger expression is the new value of count (after the increment/decrement) Postfix( count++ or count-- ) –value used in a larger expression is the original value of count (before the increment/decrement) –increment/decrement is the last operation performed (even after assignment)

Increment and Decrement If count currently contains 45, then the statement total = count++; assigns 45 to total and then 46 to count If count currently contains 45, then the statement total = ++count; assigns the value 46 to both total and count

Questions What is stored in total and count in the following statements? double total = 15.5; total++; int total = 10, count = 5; total = total + count++; int total = 20, count = 3; total = total / --count; total 16.5 total count 15 6 total count 10 2

String Concatenation A string cannot be split between two lines String greeting = "How are you doing today"; Concatenation ( + ) - produces one string where the second string has been appended to the first string String greeting = “How are you doing” + “ today?”; How are you doing today? greeting X

String Concatenation Operator + can be used to concatenate two strings or a string and a numeric value or character Precedence rules still apply Example: String str; int num1 = 12, num2 = 26; str = "The sum = " + num1 + num2; The sum = 1226 str

Questions What is the result of the following String concatenations? String str1 = "Hello"; String str2 = "World"; String str3 = str1 + " " + str2; int num1 = 10; int num2 = 2; String str = "The difference is " + (num1 - num2); The difference is 8 str Hello World str3

Summary Constants final datatype IDENTIFIER = value; –cannot be changed Variables datatype identifier; –can be changed Assignment identifier = expression; declaration

Summary Assignment –overwrites previous value –can use the variable on both sides of the expression count = count + 1; Increment/Decrement –prefix / postfix –count++; –++count;

Summary Reading Keyboard Input String Concatenation int courseNum = 110; String str = "This is COMP " + courseNum; This is COMP 110 str Scanner scan = new Scanner(); int num = scan.nextInt();

Take a Breath….And more Output –printing to the screen Parts of a Java Program Reading: Ch 2,3

Review Questions Assume that a and b are int variables. What is the value of b? a = 3; b = 4 + (++a); Given the following assignments, What is the value in str? String str; str = "The answer is "; str = str (13 + 4); 8 The answer is 1017

Output Standard output device is usually the monitor Access the monitor using the standard output object –System.out Two methods to output a string: 1.print 2.println

Using System.out System.out.print (stringExp); System.out.println (stringExp); print vs. println –after displaying stringExp, println will advance to the next line, while print does not stringExp –can be any expression where the result is a String, including string concatenation –if stringExp results in a primitive data type, it will automatically be converted to a String and output

Examples System.out.println ("Hi"); System.out.println ("There"); Hi There int num = 5; System.out.println ("The sum is " + (num + 3)); The sum is 8 int num = 5+3; System.out.println (num); 8 System.out.print ("Hi"); System.out.println ("There"); HiThere

Escape Sequences Escape character \ Used to represent special characters inside Strings Escape sequences –\n - newline –\t - tab –\b - backspace –\r - return –\\ - backslash –\' - single quote –\" - double quote

Examples System.out.println ("I said, \"Hi There!\""); I said, "Hi There!" System.out.print ("Hello\n"); System.out.println ("World"); Hello World System.out.println ("Hello\rWorld"); Hello World System.out.println ("Hi\b\bHello"); Hello System.out.println ("Hello\tWorld"); HelloWorld

Questions What is output by the following statements? System.out.println ("Helen says " + "\"What\'s up?\""); System.out.print ("Enter a number "); System.out.println ("between 1-10"); System.out.print ("\n\tplease!"); Helen says "What's up?" Enter a number between 1-10 please!

Glossary Terms Class - used to group a set of related operations (methods), allows users to create their own data types Method - set of instructions designed to accomplish a specific task Package - collection of related classes Library - collection of packages

Class Libraries A collection of classes that we can use when developing programs The Java standard class library is part of any Java development environment The System class and the String class are part of the Java standard class library

Package java.lang java.applet java.awt javax.swing java.net java.util javax.xml.parsers Purpose General support Creating applets for the web Graphics and graphical user interfaces Additional graphics capabilities and components Network communication Utilities XML document processing Packages The classes of Java library are organized into packages. Some of the packages in the standard class library are:

Using Packages We need to import some of the packages we want to use –java.util for Scanner –not java.lang because it's automatically imported for us import packageName; –import java.util.*; imports all of the classes in the java.io package –import java.util.Scanner; imports only the Scanner class from the java.util package

Using Predefined Classes and Methods long Math::round (double); To use a method you must know: –Name of class containing method (Math) –Name of package containing class (java.lang) –Name of method (round), its parameters (double a), what it returns (long), and function (rounds a to the nearest integer)

Using Predefined Classes and Methods Example method call: int num = (int) Math.round (4.6); –why don't we have to import the Math class? (Dot). Operator: used to access the method in the class

Creating a Java Program Java application program - collection of one or more classes –every application must have at least one class Class –basic unit of a Java program –collection of methods and data members Method - set of instructions designed to accomplish a specific task –print, readLine

Programming in Java Java programming language –object-oriented approach to problem solving In the Java programming language: –a program is made up of one or more classes –a class contains one or more methods –a method contains program statements A Java application always contains a method called main

Creating a Java Program All Java application programs must have a method called main –there can be only one main method in any Java application program For most of the semester, our programs will have only one class Name of source file must be ClassNameWithMain.java

Anatomy of a Java Program Syntax of class Syntax of main method public class ClassName { classMembers } public static void main (String[] args) { statement1... statementn } throws clause

Throws Clause throws clause - exceptions thrown by the main method exception - occurrence of an undesirable situation that can be detected during program execution –can either be handled or thrown readLine throws the exception IOException We won't handle the exception, we'll just throw it

Throws If we're allowing user input to the program, the heading of the main method may look like: public static void main (String[] args) throws IOException

Import Statements Tell the compiler which packages are used in the program Import statements and program statements constitute the source code Source code saved in a file with the extension.java Source code file must have the same name as the class with the main method

The main method Heading Body –statements enclosed by { } –declaration statements used to declare things such as variables –executable statements perform calculations, manipulate data, create output, accept input, etc. public static void main (String[] args)

Skeleton import statements if any public class ClassName { declare named constants and/or stream objects public static void main (String[] args) throws IOException { variable declarations executable statements }

static Heading of the main method has the reserved word static Statements to declare named constants and input stream objects are outside the main method These must also be declared with the static reserved word

Syntax –beware! a syntax error in one place might lead to syntax errors in several other places Use of semicolons, braces, commas –all Java statements end with semicolon –braces {} enclose the body of a method and cut it off from other parts of the program (also have other uses) –commas separate list items

Style Semantics –set of rules that gives meaning to a language –beware! the compiler will not be able to tell you about semantic errors (example: missing parentheses in mathematical expression) Documentation –comments - shown in green in Eclipse –naming rules use meaningful identifiers –prompt lines let the user know what type of input is expected

Style and White Space White space –blanks, tabs, blank lines –used to separate words and symbols –extra space is ignored by computer –blank line between variable declaration and rest of code Programs should be formatted to enhance readability, using consistent indentation

Comments Not used by the computer –only for human consumption Used to help others understand code –explain and show steps in algorithm –comments are essential! Should be well-written and clear Comment while coding Also called inline documentation

Java Comments // this is a one-line comment –“comments out” the rest of the line after marker // /* this is a multi-line comment */ –“comments out” everything between markers /* and */

Block-Like Multi-Line Comment /*************************************************************** * Program Insert assignment number: Insert assignment name * * Programmer: Insert your name * * Due Date: Insert due date * * Class: CSCI 51 Instructor: Dr. Joshua Stough * Recitation Section: Insert section **************************************************************/ Example Start End

/**************************************************************** * Program 0: Hello World * * Programmer: Joshua Stough * * Due Date: September 2, 2008 * * Class: COMP 14 Instructor: Dr. Joshua Stough * * Description: This program prints out a greeting to the world. * * Input: None * * Output: A friendly greeting ***************************************************************/ public class HelloWorld { public static void main(String[] args) { System.out.println ("Hello World!"); } comment class declaration main method method call

Summary Output System.out.print (stringExp); System.out.println (stringExp); –print vs. println Comments // this is a one-line comment –“comments out” the rest of the line after // /* this is a multi-line comment */ –“comments out” everything between /* and */

Next Time in CSCI 51 Objects Methods The String class Graphical User Interface (GUI)’s.