BlueJ Demo. Topic 1: Basic Java. 1. Sequencing. Features of Structured Programming Languages

Similar documents
Chapter 5 Lab Methods

St. Edmund Preparatory High School Brooklyn, NY

Chapter 5 Lab Methods

CISC-124. This week we continued to look at some aspects of Java and how they relate to building reliable software.

Last Class. While loops Infinite loops Loop counters Iterations

Programming with Java

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

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

13 th Windsor Regional Secondary School Computer Programming Competition

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

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

1. What is the difference between a compiler and an interpreter? Also, discuss Java s method.

Over and Over Again GEEN163

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements

1 Short Answer (10 Points Each)

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

ITI1120 Introduction to Computing I Exercise Workbook Fall 2012

COMP 202 Java in one week

Full file at

Please answer the following questions. Do not re-code the enclosed codes if you have already completed them.

Flow of Control: Loops. Chapter 4

Chapter 7: Arrays and the ArrayList Class

CS 302: Introduction to Programming in Java. Lecture 11 Yinggang Huang. CS302 Summer 2012

Chapter 4: Conditionals and Recursion

BASIC INPUT/OUTPUT. Fundamentals of Computer Science

Text User Interfaces. Keyboard IO plus

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

Check out how to use the random number generator (introduced in section 4.11 of the text) to get a number between 1 and 6 to create the simulation.

Chapter 1 Lab Algorithms, Errors, and Testing

Introduction to Computer Science I Spring 2010 Sample mid-term exam Answer key

Top-Down Program Development

Introduction to Software Development (ISD) David Weston and Igor Razgon

Full file at

! definite loop: A loop that executes a known number of times. " The for loops we have seen so far are definite loops. ! We often use language like

COMP 202 Java in one week

More Things We Can Do With It! Overview. Circle Calculations. πr 2. π = More operators and expression types More statements

Date: Dr. Essam Halim

1 Short Answer (10 Points Each)

Input. Scanner keyboard = new Scanner(System.in); String name;

Oct Decision Structures cont d

Loops. CSE 114, Computer Science 1 Stony Brook University

Computer Science is...

Arrays and Lists CSC 121 Fall 2014 Howard Rosenthal

Arrays and Lists CSC 121 Fall 2016 Howard Rosenthal

Chapter 4: Loops and Files

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

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

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

Array. Array Declaration:

What did we talk about last time? Examples switch statements

University of Cape Town ~ Department of Computer Science. Computer Science 1015F ~ 2007

Basic Computation. Chapter 2

CS 302: INTRODUCTION TO PROGRAMMING. Lectures 7&8

CSIS 10A Assignment 4 SOLUTIONS

Object-oriented programming in...

PROGRAMMING STYLE. Fundamentals of Computer Science I

Pace University. Fundamental Concepts of CS121 1

Introduction to Programming Using Java (98-388)

Chapter 4: Loops and Files

Example Program. public class ComputeArea {

Selections. EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG

Basic Computation. Chapter 2

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

b. Suppose you enter input from the console, when you run the program. What is the output?

COMP 110 Project 1 Programming Project Warm-Up Exercise

Midterm Examination (MTA)

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

CONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops

Introduction to Java & Fundamental Data Types

Lecture Set 2: Starting Java

Chapter 11: Create Your Own Objects

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

A+ Computer Science -

Full file at

Object Oriented Programming. Java-Lecture 6 - Arrays

Basic Computation. Chapter 2

Intro to Programming in Java Practice Midterm

Lecture Set 2: Starting Java

Arrays and Lists CSC 121 Fall 2015 Howard Rosenthal

Course Outline. Introduction to java

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Testing and Debugging

4. Java language basics: Function. Minhaeng Lee

H212 Introduction to Software Systems Honors

Decisions (If Statements) And Boolean Expressions

Java Bytecode (binary file)

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

CIS 1068 Program Design and Abstraction Spring2016 Midterm Exam 1. Name SOLUTION

COMP-202: Foundations of Programming. Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015

Chapter 5 Lab Methods

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

Using APIs. Chapter 3. Outline Fields Overall Layout. Java By Abstraction Chapter 3. Field Summary static double PI

CS111: PROGRAMMING LANGUAGE II

CSE 114 Computer Science I

Java Coding 3. Over & over again!

Discover how to get up and running with the Java Development Environment and with the Eclipse IDE to create Java programs.

Loops. EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG

Arrays and Lists Review CSC 123 Fall 2018 Howard Rosenthal

STUDENT LESSON A12 Iterations

Express Yourself. What is Eclipse?

CS61BL. Lecture 1: Welcome to CS61BL! Intro to Java and OOP Testing Error-handling

Transcription:

Topic 1: Basic Java Plan: this topic through next Friday (5 lectures) Required reading on web site I will not spell out all the details in lecture! BlueJ Demo BlueJ = Java IDE (Interactive Development Environment) Editor + Compiler + Interpreter + other tools Remember: no "run" button; just execute main function My goal: highlight differences between Java and Python mention things that often trip up Java newbies file I/O Information about 3 Java tools on web site: BlueJ JDK plus text editor Eclipse Other alternatives OK as long as based on standard Sun (Oracle) Java, version 6 or 7 (also known as 1.6 or 1.7) 1 2 Features of Structured Programming Languages basic statements: assignments, function calls... compound statements: 1. Sequencing: one statement after another 2. Selection: choosing among alternatives 3. Iteration: repeating a statement 4. Grouping: treating several statements as a unit abstraction: functions/methods/procedures with parameters & results 1. Sequencing Python: separate one statement from the next by going to the next line (or midline semicolon) a = 7 b = 8 c = 5; d = 6 e = 1 + 2 + 3 + \ 4 + 5 Java: All simple statements end with a semicolon. a = 7; b = 5; c = 1 + 2 + 3 + 4 + 5; d = 6; 3 4

Python: if a > b: c = 17 else: c = 5 2. Selection Python: if n > 10: a = 1 b = 2 c = 3 3. Grouping What statements are executed only when n > 10? How do you know? Java: if (a>b) c = 17; else c = 5; or (ugly but legal): if (a> b) c = 17; else c = 5; Java: if (n > 10) { a = 1; b = 2; c = 3; Green part is called a block. Combines a group of statements into a compond statement. Java also has a switch statement for multi-way branches. Optional for 124. Ugly but legal equivalent: if (n>10) {a = 1; b = 2; c = 3; 5 6 4A. Iteration: While loops 4B. Iteration: For loops Python: while i < n: total += i i += 1 Java: while (i < n) { total += i; i++; Python: for i in range(n): total += i Java: for (int i = 1; i < n; i++) { total += i; Java also has a third kind of loop: do/while Optional for 124. same as: int i = 1; while (i < n) { total += i; i++; 7 8

Dynamic vs. Static Typing Declaring Variables Python uses dynamic typing: must run program to determine the types of expressions if <some condition>: x = 14 else: x = "abc" # what is the type of x??? # is x/4 a legal expression??? Java uses static typing: the value of every expression can be determined at compile time. Every variable must be declared with a type. Or: Rules: int x = 14; String y = "abc"; int x; // later on in program X = 14; A variable must be declared before it is set (possibly on the same line) A variable must be set before it is used 9 10 Nuisance public static void main(string args[]) { int x;.. if (<some error condition>) { System.out.println("error!"); System.exit(1); // aborts program else {... x =...; int y = x + 17; WILL NOT COMPILE!... // end main volume of a cone = In Java: Mixed-Mode Arithmetic double height = 10.6; double radius = 5.24; final double PI = 3.14159; double volume = 1/3 * PI * radius * radius * height; System.out.println(volume); result? why? 1 3 π r 2 h 11 12

Strings The "+" Operator Strings are objects Not lists/arrays String literal: "abcd" Character literal 'a' 'a' and "a" are not the same thing! To access parts of strings, use special String methods: charat length substring int x = 1; int y = 2; // value of x + y? String x = "abc"; String y = "def"; // value of x + y? String x = "one"; int y = 2; // value of x + y? 13 14 The "+" Operator (continued) Comparing Strings (equality) int a = 9; int b = 6; System.out.println("the total is " + a + b); // what is printed? int c = 9; int d = 6; System.out.println(c + d + " is the total"); // what is printed? String s1 = "abcd"; String t = "ab"; prints "not equal"! String u = "cd"; String s2 = t + u; if (s1 == s2) System.out.println("equal"); else System.out.println("not equal"); if (s1.equals(s2)) prints "equal" System.out.println("equal"); else System.out.println("not equal"); 15 16

Comparing Strings (inequality) String a = "apple"; String b = "banana"; int val = a.compareto(b); Output To The Console System.out.print(s) System.out.println(s) compareto returns: 0 if a and b are exactly equal positive int if a is greater than b negative int if a is less than b 17 18 Input From the Keyboard Input, continued 1. Create a Scanner object: Scanner keyboard = new Scanner(System.in); keyboard.hasnextint() true if next token is an integer 2. Use one of the reading methods: keyboard.next(): next "token" as String keyboard.nextline(): rest of current line as String keyboard.nextint(): next token, converted to integer keyboard.nextdouble(): next token, converted to double Example programs: ScannerDemo: basic input of integers & strings; we will add checking ReadLines: reading tokens & whole lines can be tricky 19 20

Reading From a File Needs knowledge of exceptions later this term. For now: helper class FileOpen available on web site. To use FileOpen: add copy to the same folder as your program. (No import necessary.) Methods What is a method? Like a function in Python. Small piece of a program Performs small task Other names in different languages: function, procedure, subprogram, subroutine String inputname = "myfile.txt"; Scanner inputfile = FileOpen.openScanner(inputName); PrintWriter outputfile = FileOpen.openWriter("output.txt"); // use outputfile just like System.out Look at FileOpenDemo... Why do we use methods? avoid duplicated code modularize improve readability readability means: easier to debug easier to modify harder to goof 21 22 Parameters & Return Results Abstraction parameter: information you give to the method return result: information it gives back method with no result is "void" example: leapyear method abstract view of leapyear method: what it does (interface) concrete/implementation view: how it works (implementation) Every method must have a header comment saying what it does Include parameters, return result, possible errors To learn how to call the method: just read the header comment To learn how the method works: read the body too 23 24

Ending Things Early 1. break statement ends the current (innermost) loop 2. return ends the current method Order Of Methods Common question: Does the order in which I declare my methods matter? Answer: For functionality, no. For style, maybe yes. 3. System.exit(n) ends the program convention: n = 0 means normal exit n 0 parameter means error abort Example: Endings.java 25 26 Overloading Scope OK to have two methods with the same name. Call is resolved based on number and/or types of parameters public static double m(double a, double b) { public static String m(int a, int b) { return a + 2*b; return a + b.substring(1); public static double m(double a, double b, double c) { return (a+b+c)/3.0; Scope of variable = where it can be used Scope of a Java variable: from declaration to end of block public static int scope() { int a =...; while (a > 0) { int b =...; for (int i = 0; i < b; i++) { int c = b+i; a += c; while (...) { double c =...;... // end while // end while return a; // end scope 27 28

Scope (2) You can't hide a variable by declaring a variable with the same name in an inner loop. Global Variables You can declare variables outside of any methods -- "globally". Don't do it until we discuss it in the next topic! int a =...; while (a > 0) { int b =...; if (...) { int b =...; // illegal! // end while 29 30 Right now: Arrays basics of one- and two-dimensional arrays lets us use arrays in examples, assignments and quizzes Caution to Python Programmers Arrays are not lists!!!! ignores some details After classes topic we'll fill in some missing details Python Lists: can grow & shrink can mix many types of values (heterogeneous) languages features for adding & deleting at any position Java Arrays: size is specified at creation time, never changes all values must have same type (homogeneous) more programming effort required to add & delete array elements 31 32

Definitions Creating An Array array: ordered collection of elements of the same type [homogeneous collection] Note: indexes go from 0 to length-1 index: position of element length: number of elements in array Size of array specified when created. size can never change! 0 1 2 3 4 5 6 General form: <type>[] <name> = new <type>[<size>] or: <type> <name>[] = new <type>[<size>] Examples: int marks[] = new int[20]; String[] names = new String[10]; In each of above, there are two things happening: 1. Declaring the array variable 2. Creating a new array and assigning it to the variable 33 34 1. Declaring an Array 2. Creating a New Array syntax: <type> <name>[]; or: <type>[] <name>; declaration int coursemarks[]; coursemarks has not been initialized use an array constructor to give it a value: coursemarks = new int[20]; Note: no length specified! examples: int coursemarks[]; String args[]; double[] data; now coursemarks is an array containing 20 integers: indexes 0 to 19 all elements automatically initialized to zero or combine declaration & initialization: int coursemarks[] = new int[20]; 35 36

Using an Array refer to an element of an array as <array name> [ <index> ] // read values into array int coursemarks[] = new int[20]; for (int i = 0; i < 20; i++) { System.out.print("enter next mark: "); coursemarks[i] = keyboard.nextint(); // end for Style problem: 20 used in several places. Why is that // average the values bad? int sum = 0; for (int i = 0; i < 20; i++) sum = sum + coursemarks[i]; System.out.println("average mark: " + (double) sum / 20); Using an Array: Improved Version // read values into array final int NUM_STUDENTS = 20; int coursemarks[] = new int[num_students]; for (int i = 0; i < NUM_STUDENTS; i++) { System.out.print("enter next mark: "); coursemarks[i] = keyboard.nextint(); // end for // average the values int sum = 0; for (int i = 0; i < NUM_STUDENTS; i++) sum = sum + coursemarks[i]; System.out.println("average mark: " + (double) sum / NUM_STUDENTS); 37 38 Even Better Version every array object has length attribute <array name>.length gets the length of the array Bounds Checking Java throws an exception (aborts) if you try to access or change an array element that's out of bounds int coursemarks[] = new int[20]; for (int i = 0; i<coursemarks.length; i++){ System.out.print("enter next mark: "); coursemarks[i] = keyboard.nextint(); // end for int sum = 0; for (int i = 0; i < coursemarks.length; i++) sum = sum + coursemarks[i]; System.out.println("average mark: " + (double) sum / coursemarks.length); Example: int myarray[] = new int[10]; int x = myarray[0]; // OK myarray[9] = 42; // OK int z = myarray[10]; // exception! myarray[-1] = 7; // exception! java.lang.arrayindexoutofboundsexception at ArrayTest.main(ArrayTest.java:9) 39 40

Arrays As Parameters public class ArrayParm { public static void changearray(int numbers[]) { numbers[0]++; // end changearray Two-Dimensional Arrays assignment scores for 20 students, 9 assignments: int scores[][] = new int[20][9]; visualize as a table: 20 rows, 9 columns public static void main(string args[]) { int years[] = new int[3]; years[0] = 1987; years[1] = 1989; years[2] = 1994; changearray(years); for (int i = 0; i < years.length; i++) System.out.println(years[i]); // end main // end class student number 3, assignment 6: scores[3][6] 41 42 2D Arrays &.length Java treats a 2D array as an array of arrays. int scores[][] = new int[20][9]; scores is a 2D array of ints scores[4] is a 1D array of ints (the 5 th row) scores[4][7] is an int What does scores.length mean? number of rows (20) the height of the array Example: Total of 2D Array int numbers[][] =...; // initialize numbers... int total = 0; for (int row = 0; row < numbers.length; row++) { for (int col = 0; col < numbers[row].length; col++) { total += numbers[row][col]; // end for How would you ask for the number of columns (width)? scores[0].length 43 44

Using Java API Classes 1. Spell Out Full Name of Class API is divided into packages. Example Scanner class is in java.util package. Three ways to use Scanner. public class Import { public static void main(string args[]) { java.util.scanner keyboard = new java.util.scanner(system.in); System.out.print("Enter your name: "); String name = keyboard.nextline(); System.out.println("Hello, " + name + "!"); // end main // end class 45 46 2. Import Class From Package 3. Import All Classes From Package import java.util.scanner; public class Import { public static void main(string args[]) { Scanner keyboard = new Scanner(System.in); System.out.print("Enter your name: "); String name = keyboard.nextline(); System.out.println("Hello, " + name + "!"); // end main // end class import java.util.*; public class Import { public static void main(string args[]) { Scanner keyboard = new Scanner(System.in); System.out.print("Enter your name: "); String name = keyboard.nextline(); System.out.println("Hello, " + name + "!"); // end main // end class This is no more expensive than importing just Scanner. 47 48

Special Class: java.lang Caution Automatically imported into all Java programs. Includes standard useful classes including: Math In CISC 124 you may use any API class unless specifically asked not to (for assignments, quizzes, etc) System String You may NOT use non-standard classes & packages (downloaded from Internet, supplied with Eclipse, etc.) 49 50 FAQ Programming Style What's the point of the parameter of the main method?? (Or the parameter to System.exit?) Both are for using Java with a command-line system (DOS, Linux, Mac terminal) Demo... To be useful, a program has to work correctly. Also must be readable by human beings. Examples... Some assignments will have style points. In-class exercises discussing examples of student assignments (anonymously) Not needed for CISC 124. Quizzes & Exams: time pressure, no style points BUT: I can't give you points if I can't understand what you write! Style can mean more partial credit for incorrect code 51 52