Lab # 2. For today s lab:

Similar documents
Introduction to Java. Java Programs Classes, Methods, and Statements Comments Strings Escape Sequences Identifiers Keywords

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 3: SEP. 13TH INSTRUCTOR: JIAYIN WANG

Computer Hardware. Java Software Solutions Lewis & Loftus. Key Hardware Components 12/17/2013

A PROGRAM IS A SEQUENCE of instructions that a computer can execute to

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

COMP 202 Java in one week

Java Bytecode (binary file)

Lesson 1A - First Java Program HELLO WORLD With DEBUGGING examples. By John B. Owen All rights reserved 2011, revised 2015

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

CS 177 Recitation. Week 1 Intro to Java

Programming in Java Prof. Debasis Samanta Department of Computer Science Engineering Indian Institute of Technology, Kharagpur

CS 152: Data Structures with Java Hello World with the IntelliJ IDE

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

Identifiers. Identifiers are the words a programmer uses in a program Some identifiers are already defined. Some are made up by the programmer:

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 2: SEP. 8TH INSTRUCTOR: JIAYIN WANG

Course Outline. Introduction to java

Full file at

Chapter 2: Programming Concepts

Section 2: Introduction to Java. Historical note

Computer Programming : C++

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

Lecture Set 2: Starting Java

Introduction to Java Applications

COMP 110 Project 1 Programming Project Warm-Up Exercise

Chapter 1. Introduction

Lecture Set 2: Starting Java

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

Software and Programming 1

Lecture (01) Getting started. Dr. Ahmed ElShafee

Outline. Overview. Control statements. Classes and methods. history and advantage how to: program, compile and execute 8 data types 3 types of errors

Basic Programming Language Syntax

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

The name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet.

Java Programming Fundamentals - Day Instructor: Jason Yoon Website:

CONTENTS: What Is Programming? How a Computer Works Programming Languages Java Basics. COMP-202 Unit 1: Introduction

List of Slides 1 Title 2 Chapter 2: Sequential execution and program errors 3 Chapter aims 4 Section 2: Example:Hello world 5 Aim 6 Class: programs ar

Get JAVA. I will just tell you what I did (on January 10, 2017). I went to:

Project 1. Java Control Structures 1/17/2014. Project 1 and Java Intro. Project 1 (2) To familiarize with

3 CREATING YOUR FIRST JAVA APPLICATION (USING WINDOWS)

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

Mobile App:IT. Methods & Classes

COMP163. Introduction to Computer Programming. Introduction and Overview of the Hardware

First Java Program - Output to the Screen

Getting Started (1.8.7) 9/2/2009

UEE1302 (1102) F10: Introduction to Computers and Programming

Chapter 2 Author Notes

Chapter 1: A First Program Using C#

Elementary Programming

Introduction to Java Applications; Input/Output and Operators

2 Getting Started. Getting Started (v1.8.6) 3/5/2007

Programming with Java

Pace University. Fundamental Concepts of CS121 1

Chapter 1 Lab Algorithms, Errors, and Testing

17 Hello world 18 Type: String: literal 19 Standard API: System: out.println() 20 Hello world 21 Statement 22 Statement: simple statements are ended w

Program Fundamentals

Software and Programming 1

Creating a C++ Program

Introduction to OOP Using Java Pearson Education, Inc. All rights reserved.

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

SDKs - Eclipse. SENG 403, Tutorial 2

Class 1: Homework. Intro to Computer Science CSCI-UA.0101 New York University Courant Institute of Mathematical Sciences Fall 2017

Introduction. Introduction to OOP with Java. Lecture 01: Introduction to OOP with Java - AKF Sep AbuKhleiF -

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

CSCI 161: Introduction to Programming I Lab 1b: Hello, World (Eclipse, Java)

Getting started with Java

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

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

PROGRAMMING STYLE. Fundamentals of Computer Science I

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

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

COMP 202 Java in one week

COMP-202 Unit 4: Programming with Iterations

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M

7/8/10 KEY CONCEPTS. Problem COMP 10 EXPLORING COMPUTER SCIENCE. Algorithm. Lecture 2 Variables, Types, and Programs. Program PROBLEM SOLVING

Chapter 1. Introduction to Computers and Java Objects. Background information. » important regardless of programming language. Introduction to Java

Java Language. Programs. Computer programs, known as software, are instructions to the computer. You tell a computer what to do through programs.

CS125 : Introduction to Computer Science. Lecture Notes #4 Type Checking, Input/Output, and Programming Style

Supplement D: Expanded Guidelines on Programming Style and Documentation

Math Modeling in Java: An S-I Compartment Model

Outline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail.

Slide 1 Java Programming 1 Lecture 2D Java Mechanics Duration: 00:01:06 Advance mode: Auto

Lesson 1: Writing Your First JavaScript

COMP-202: Foundations of Programming. Lecture 2: Variables, and Data Types Sandeep Manjanna, Summer 2015

Variables and Constants

CS 231 Data Structures and Algorithms, Fall 2016

Expanded Guidelines on Programming Style and Documentation

Introduction to Computers and Java

Week 2: Data and Output

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

A A B U n i v e r s i t y

Tutorial No. 2 - Solution (Overview of C)

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

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 8: SEP. 29TH INSTRUCTOR: JIAYIN WANG

Tutorial 1 CSC 201. Java Programming Concepts عؾادئماظربجمةمبادؿكدامماجلاصا

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

CS 351 Design of Large Programs Coding Standards

Introduction to IntelliJ

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

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic

CS 251 Intermediate Programming Coding Standards

Transcription:

1 ITI 1120 Lab # 2 Contributors: G. Arbez, M. Eid, D. Inkpen, A. Williams, D. Amyot 1 For today s lab: Go the course webpage Follow the links to the lab notes for Lab 2. Save all the java programs you find there in the C:\work directory. We'll be using them later. 2

2 Introduction to Java Editing, compiling, and running Java programs Syntax, comments To get to the point that you can write Java programs: Declare variables Read data from the keyboard Numbers, Operators, Calculations Print the results. Translate a simple algorithm into Java 3 Translation in Java Do you recall this image you have seen in class? Java source code Java compiler Java bytecode Java Bytecode Interpreter compiler (Java Virtual Machine) Machine code 4

3 Basic Program Development These are the steps you will be following today. Edit and save program errors errors Compile program Execute program and evaluate results 5 Editing a Java program An editor is used to create and modify a program. The program is just an ordinary text file, so you can use any text editor You don't need to use a special one, although editors specifically for programs can be much more convenient. This text file with the program in it is called the source file for the program Java source files have the extension.java 6

4 Compiling The source file - the program in textual format - cannot be directly executed. It needs to be translated into an executable form. A compiler also checks for certain types of errors, called syntax errors. If it detects an error you need to figure out what caused the problem and go back and edit the the source file to fix the problem. 7 Syntax Errors A grammatical error Example: whle instead of while Found by compiler ( compiler-time error ) Automatically found Usually the easiest to fix Cannot run code until all syntax errors are fixed in all open files. Be careful when reading messages from the compiler: Problems are described from a grammatical point of view. Sometimes, the message is a best guess of what might be wrong, and may be misleading. 8

5 Run If the compiler detects no problems, it creates a byte code file having a.class extension. It does not automatically run your program - that is done by yyou manually. Since the.class file stays around you can run it whenever you like, you don't have to recompile every time. But of course if you change the source code you must manually recompile or you'll be using the old executable. Once the program is running it is important to test it to make sure it produces correct answers. You'll usually run it may times on various inputs to make sure it works fine under all circumstances. If you find it is producing the wrong answer, you have to debug the program this will involve editing the program (the source file), recompiling, rerunning. 9 Exercise 1 - Overview of a Java Program Start Dr. Java Open ( load ) the file Prog1.java You should already have saved this file on your hard drive). 10

6 Compiling the Java Program To compile Prog1.java with Dr. Java, click on the button Compile. This will compile all files listed in the left window. Compiler messages appear under the tab Compiler Output at the bottom of the window. Shows if the compilation was successful. Otherwise the compiler produces error messages. In the directory where Prog1.java is stored The compiler will have produced the file Prog1.class 11 Running a Program Now that the program is compiled, you can run it Click on Run (or type F2) This will execute the method main of the program you edited. In the Interactions zone (see tab at the bottom), you will see the program output You can also click on the tab Console to see only program output with any messages generated by Dr. Java 12

7 General Organization Source file contains a CLASS. We will always have one class per file. A CLASS contains one or more METHODS. A METHOD contains declarations, statements, and control structures. This is where you will implement your algorithms. A PROGRAM must include a class that has a method called main We shall see in the second half of the course how many classes can make up a program. COMMENTS can be placed anywhere. 13 Comments Comments are for people reading your program. In them you explain your program in English. The compiler completely ignores them. In Java Comments may be placed anywhere you like. On any line, everything after // (to the end of the line) is a comment. Anything in between /* and */ is a comment (including multiple lines) See Prog1.java as for examples 14

8 Types of comments Single line comment Everything from // to the end of the line is the comment some code // This is a comment more code General comment Everything from /* to the next occurrence of */ is a comment Can be part of a line code /* comment */ more code Can be several lines code /* start of comment more comment end of comment */ more code 15 Class Definition Has these parts: Keyword class A keyword is a word that has special meaning in the Java language. Dr. Java highlights these reserved words by colouring them blue. In this case the keyword class tells the compiler that you are beginning the definition of a class. A name for the class Prog1 is the name of a class Methodes An opening { <-- this symbol is called a brace or curly bracket One or more method definitions A closing } Braces are used to enclose lines of code together to form an instruction block. 16

9 Identifiers The class has the name Prog1 In programming, g, the official term for the name is an identifier. Identifiers are used to name many things: classes, methods, variables, etc. There are rules for identifiers in Java Only use the digits 0-9, letters A-Z a-z, the characters $ and _ Identifiers cannot start with $ and it is not recommended to start them with _ (underscore) 17 main method definition The definition of main starts with a line that we will never change for this course: public static void main(string[] args) main is the name of this method; it is a special identifier, like a keyword. The purpose of the main method is to tell Java, when you run the program, start here. After this opening line comes: An opening { The "body" of the method - in the example program main's body consists of two statements A closing } Next week in the lab session, we shall add another method that will be called by main. 18

10 The println and print statements The simplest forms: System.out.println( "some string" ); Go to the next line System.out.print ( "some string" ); Stays on the same line, any new printed character or typed in character will follow the message A STRING is a collection of characters, contained in double quotes to mark the start and the end of the string. Whatever is between the double-quotes is written ("printed") on the console (the screen). After the string is printed, the cursor marking the location of where the computer will print next is moved to the start of a new line. Note: the quotes are not part of the string. 19 The import Statement Indicates to the compiler which libraries (or set of predefined classes/methods) the program uses (or may potentially use). In Prog1.java, we are interested in all classes (*) and input/output methods (io). For example, this import includes System.out.println The current version of Java does not require this particular import; it is done automatically There can be many import, usually placed at the start of the file (and always before any of its classes are used). 20

11 Syntax - General Features Java is "free format". In general, you can have blank lines and space things the way you like. However, there are some restrictions for how to space and place things. You cannot put spaces (or line breaks) in the middle of names or keywords. There are conventions to make programs more readable and understandable by many people (e.g. indentation). Java is case-sensitive. class and Class are two different words keywords never use capitals This is a common source of bugs Java is VERY PARTICULAR about punctuation. If you miss a semicolon or have mismatched brackets or braces or double-quotes, or if you use a single quote (or two) instead of a double quote, you'll get a syntax error. 21 Some general rules are: All brackets must match with a bracket of the same type, opposite direction (open and close pairs) The open-close pairs must fit ( nest ) inside each other You can t do this: ( [ ) ] Double quotes must match up ON THE SAME LINE All statements end with a ; (semicolon) Braces are normally NOT followed by a semicolon (there are some exceptions in special cases). The class name and the file name should be the same (except of course for the.java extension on the file name). 22

12 Exercise 2 Prog2 Try the same thing with Prog2.java What happened? 23 Prog2 You will get error messages because there is one mistake in Prog2.java (the quote to end the string in the println statement is missing). This is what syntax error messages look like Where does it say what line the error occurred on? Why does the compiler think there are two errors? Hint: Notice that Dr. Java colours strings red. Nt Note carefully fll what ht is coloured red in this program. Fix the error, and re-compile When you fix the error, notice the difference in what is coloured red. 24

13 Exercise 3 Prog3 This program illustrates one of the most common errors. Try it! 25 Exercise 4 Prog4 This program shows the difference between println and print. Try it! 26

14 Exercise 5 Prog5 Try to compile and run this program. What happened? 27 Exercise 6 - Prog6 - Correcting Syntax Errors Correct all errors in Prog6.java so that it will produce the following output:!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! This program used to have lots of problems, but if it prints all the lines on the screen, you fixed them all. *** Hurray! ***!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 28

15 Exercise 7 Working with a Circle The algorithm on the following slide defines a simple program that Gets a circle radius from the user, Calculates the area. Displays the result. The constant value of 3.14 is used for π. translate the algorithm to a Java method The main method in Java calls this algorithm. Compile and test the program. 29 Exercise 7 (algorithm CalculateArea) GIVENS: Radius (the radius of the circle) RESULTS: Area (the area) INTERMEDIATES: Pi (a constant, 3.14) HEADER: Area<- CalculateArea(Radius) BODY: Pi 3.14 Area Pi x Radius x Radius 30

16 Exercise 7 (main algorithm) GIVENS: (none) RESULTS: (none) INTERMEDIATES: Radius (the radius of the circle) Area (the area) HEADER: main() BODY: Print( Please enter a value for radius: ) Radius ReadReal() Area CalculateArea( Radius) PrintLine( The area of the circle is, Area) 31 Trace the algorithm CalculateArea for Radius = 7 Table 1 (Prog7) CalculateArea(7) Statement Radius Pi Area Initial values 7?? 1. Pi <- 3.14 3.14 2. Area <- Pi x Radius x Radius 153.86 32

17 Implement the Java program 33