Installing Java. Tradition. DP Computer Science Unit 4.3: Intro to programming 1/17/2018. Software & websites

Similar documents
byte b = 1; // 8 bits short s = 2; // 16 bits

Key Concept: all programs can be broken down to a combination of one of the six instructions Assignment Statements can create variables to represent

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Today s plan Discuss the Bb quiz 1 Clarify Lab 1 Review basic Java materials Classes, Objects, Interfaces Strings Java IO. Understanding Board

Getting started with Java

Today s plan Discuss the Lab 1 Show Lab 2 Review basic Java materials Java API Strings Java IO

Java Basic Programming Constructs

Building Java Programs. Chapter 2: Primitive Data and Definite Loops

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8

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

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

Java Foundations: Introduction to Program Design & Data Structures, 4e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

DM503 Programming B. Peter Schneider-Kamp.

Course Outline. Introduction to java

CMPT 125: Lecture 3 Data and Expressions

Basic Operations jgrasp debugger Writing Programs & Checkstyle

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

! Widely available. ! Widely used. ! Variety of automatic checks for mistakes in programs. ! Embraces full set of modern abstractions. Caveat.

Decisions in Java IF Statements

AP Computer Science A

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

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

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

AP Computer Science Unit 1. Programs

DM550 Introduction to Programming part 2. Jan Baumbach.

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

Over and Over Again GEEN163

Mr. Monroe s Guide to Mastering Java Syntax

Building Java Programs

DM550 Introduction to Programming part 2. Jan Baumbach.

Object-Oriented Programming

CS111: PROGRAMMING LANGUAGE II

Object Oriented Programming. Java-Lecture 1

M105: Introduction to Programming with Java Midterm Examination (MTA) Makeup Spring 2013 / 2014

Building Java Programs

DM537 Object-Oriented Programming. Peter Schneider-Kamp.

Important Java terminology

Building Java Programs

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

COMP-202 Unit 4: Programming with Iterations

Data Structure and Programming Languages

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Arrays: An array is a data structure that stores a sequence of values of the same type. The data type can be any of Java s primitive types:

1. Download the JDK 6, from

Iteration statements - Loops

Midterm Examination (MTA)

Any serious Java programmers should use the APIs to develop Java programs Best practices of using APIs

1 Short Answer (10 Points Each)

cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1

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

CMSC131. Introduction to your Introduction to Java. Why Java?

StudyHub+ 1. StudyHub: AP Java. Semester One Final Review

Lecture 2: Intro to Java

Warm up question. 2)Which of the following operators are defined on a half integer? Which of the following would it be useful to write as behaviors?

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

ITERATION WEEK 4: EXMAPLES IN CLASS

4 WORKING WITH DATA TYPES AND OPERATIONS

CS Programming I: ArrayList

Lecture Notes CPSC 224 (Spring 2012) Today... Java basics. S. Bowers 1 of 8

McGill University School of Computer Science COMP-202A Introduction to Computing 1

Full file at

Programming Constructs Overview. Method Call System.out.print( hello ); Method Parameters

Object-Oriented Programming. Topic 2: Fundamental Programming Structures in Java

Flow of Control. Chapter 3

What did we talk about last time? Examples switch statements

CS212 Midterm. 1. Read the following code fragments and answer the questions.

CS 106 Introduction to Computer Science I

Topic 4 Expressions and variables

C212 Early Evaluation Exam Mon Feb Name: Please provide brief (common sense) justifications with your answers below.

CS163/164 Final Exam Study Session

Primitive Data, Variables, and Expressions; Simple Conditional Execution

1.1 Your First Program

COSC 123 Computer Creativity. Java Lists and Arrays. Dr. Ramon Lawrence University of British Columbia Okanagan

Building Java Programs

COMP 202 Java in one week

St. Edmund Preparatory High School Brooklyn, NY

CS111: PROGRAMMING LANGUAGE II

Faculty of Science COMP-202A - Introduction to Computing I (Fall 2008) Midterm Examination

Java. Programming: Chapter Objectives. Why Is Repetition Needed? Chapter 5: Control Structures II. Program Design Including Data Structures

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

Notes from the Boards Set BN19 Page

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

CS 200 Using Objects. Jim Williams, PhD

Building Java Programs Chapter 2

Tutorial # 4. Q1. Evaluate the logical (Boolean) expression in the following exercise

Lecture Set 4: More About Methods and More About Operators

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

COE 212 Engineering Programming. Welcome to the Final Exam Monday May 18, 2015

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

Introduction to Computer Programming

Classes Basic Overview

CSC 1214: Object-Oriented Programming

Java Language Basics: Introduction To Java, Basic Features, Java Virtual Machine Concepts, Primitive Data Type And Variables, Java Operators,

Oct Decision Structures cont d

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

1 Short Answer (15 Points Each)

Software Practice 1 Basic Grammar

Loops. Eng. Mohammed Abdualal. Islamic University of Gaza. Faculty of Engineering. Computer Engineering Department

Transcription:

DP Computer Science Unit 4.3: Intro to programming Installing Java Software & websites JDK (Java development kit) download: http://www.oracle.com/technetwork/java/javase/ Tradition For a full IDE (integrated development environment): https://www.jetbrains.com/idea/ For a web based environment for practice: https://repl.it/languages/java Useful reference site: https://www.tutorialspoint.com/java/ https://stackoverflow.com/ 1

Hello world Boiler plate (get used to it it s Java) Print & input Variables int a = 1; float f = 1.0; String s = "hello"; boolean b = false; 2

Printing System.out.print() System.out.println() Eg: System.out.println("Hello world"!); Input java.util.scanner reader = new java.util.scanner(system.in); String t = reader.nextline(); Or: String message = "Hello world"; System.out.println( message ); Input & print example java.util.scanner reader = new java.util.scanner(system.in); Numbers System.out.print( "What's your name?" ); String personname = reader.nextline(); System.out.println( "Hello " + personname ); 3

Data types Numerical operations int a = 1; double d = 1.0; String s = "hello"; boolean b = false; int a = 5; int b = 4; System.out.println( a + b ); System.out.println( a b ); System.out.println( a * b ); System.out.println( a / b ); System.out.println( a % b ); // addition // subtraction // multiplication // division // modulus (remainder) Integer v float division? PEMDAS int a = 20; int b = 6; System.out.println( a / b ); System.out.println( a % b ); System.out.println( 2 + 4 * 3 ); // 14 or 18? double c = 20; double d = 6; System.out.println( c / d ); System.out.println( c % d ); 4

Inputting numbers java.util.scanner reader = new java.util.scanner(system.in); String t = reader.nextline(); int i = reader.nextint(); double d = reader.nextdouble(); Input number example java.util.scanner reader = new java.util.scanner(system.in); System.out.print("Type a number:"); int i = reader.nextint(); System.out.print("You typed "); System.out.print( i ); System.out.print(", the next number is "); System.out.println( i+1 ); Casting (converting) int num = Integer.parseInt( str ); int num = (int)math.round( d1 ); double d1 = Double.parseDouble( str ); double d1 = (double)i; String str = Integer.toString( num ); String str = Double.toString( d ); // String to int // double to int // String to double // int to double // int to String // double to String If then else 5

If / If else / If else if else Conditions: Comparing numbers if ( condition ) { if ( condition ) { else { if ( condition ) { else if ( condition ) { else { (a == b) IS EQUAL TO (a!= b) IS NOT EQUAL TO (a < b) IS LESS THAN (a <= b) IS LESS THAN OR EQUAL TO (a > b) IS GREATER THAN (a >= b) IS GREATER THAN OR EQUAL TO Conditions: Comparing strings Conditions: Multiple TESTING EQUALITY OF VALUE Objects.equals(s1, s2) s1.equals(s2) USE THIS OLD METHOD YOU'LL SEE USED ONLINE ( condition1 && condition2 ) AND ( condition1 condition2 ) OR (! condition1 ) NOT COMPARING ORDER OF VALUE s1.compareto(s2) == 0 when string values match == negative when s1 is alphabetically 1 st == positive when s1 is alphabetically 2 nd 6

For ever while I say so For & while loops for ( initialization ; comparison ; iteration ) { instructions(); while ( comparison ) { instructions(); Exactly the same for ( int i=0 ; i<10 ; i++ ) { System.out.println( i ); int i=0; while ( i<10 ) { System.out.println( i ); i++; How long is a piece of string? 7

String manipulation String s1 = "hello"; String s2 = "What does the fox say?"; s1.length(); // 5 s1.charat(0); // "h" s1.codepointat(0); // 104 (unicode) s2.indexof("fox"); // 14 s2.lastindexof("fox"); // 14 s2.substring(14,17); // fox s2.replace("fox","goat"); // What does the goat say? String manipulation String s1 = "hello"; String s2 = "What does the fox say?"; s2.touppercase(); s2.tolowercase(); String s3 = "Hi there! " + s2; // WHAT DOES THE FOX SAY? // what does the fox say? // concatenation String[] words = s2.split(" "); // ["What","does","the","fox","say?"] String manipulation Want to change an individual letter inside a string? Unlike other languages, you can not do str[2] = 'x' or similar. Java Strings are immutable (unchangeable). Most "simple" solution... Making a list and checking it twice String myname = "halftime"; myname = myname.substring(0,4) + 'x' + myname.substring(5); System.out.println(myName); // halfxime 8

Arrays v ArrayLists ARRAYS Fixed in size Simple structure import java.util.arrays; You need to know both ARRAYLISTS Resizable More complicated to use import java.util.arraylist; Arrays: Declaring int[] primes = new int[10]; primes[0] = 1; primes[1] = 2; primes[2] = 3; primes[3] = 5; primes[4] = 7; primes[5] = 11; primes[6] = 13; primes[7] = 17; primes[8] = 19; primes[9] = 23; int[] primes = {1,2,3,5,7,11,13,17,19,23; Two ways to do the same thing. Plus/minus each method? Arrays: Using java.util.arrays import java.util.arrays; for (int item : primes) { System.out.println( item ); for (int i=0; i<primes.length; i++) { System.out.println( primes[i] ); Just for something different two different ways to do a for loop through an array. Plus / minus each approach? // Check if two arrays are filled with matching values if ( Arrays.equals( primes, other )) { System.out.println("The two arrays match"); // Sort an array in ascending order Arrays.sort( primes ); // Create a string listing the contents of the array // output: [1, 2, 3, 5, 7, 11, 13, 17, 19, 23] System.out.println( Arrays.toString( primes )); 9

ArrayList: Declaring ArrayList: Using ArrayList<String> alist = new ArrayList<String>(); alist.add("first"); alist.add("second"); String item = alist.get(2); int size = alist.size(); alist.remove(3); // Remove 4 th item (index==3) Collectionssort(alist); for (String item : alist) { System.out.println( item ); Converting Example include java.io.file; include java.utils.arraylist; include java.utils.scanner; Array to ArrayList ArrayList arrlist = new ArrayList<>(Arrays.asList(arr)) ArrayList to Array (assuming it is String change as appropriate) String[] arr = (String[])arrlist.toArray(new String[arrlist.size()]); // load contents of a file into an arraylist File f = new File("/path/to/filename.ext"); Scanner reader = new Scanner(file); ArrayList<String> content = new ArrayList<String>(); while (reader.hasnextline()) { content.add(reader.nextline()); reader.close(); 10

Functions Functions A function is a simple way of being able to re use code. In Java the basic rule of syntax is: public static returntype functionname(paramtype param1, ) { // insert code return value; Example: Quadratic formula sort of public static double quadratic(double a, double b, double c) { double x = ( -b + Math.sqrt( b*b - 4*a*c ) ) / ( 2*a ); return x; public static void main(string[] args) { double result = quadratic(2,-4,-8); System.out.println( result ); Example 2: Calculate average public static double average(int[] numbers) { int sum = 0; for ( int number : numbers ) { sum = sum + number; return( (double)sum / (double)numbers.length ); public static void main(string[] args) { int[] a = { 3, 6, 9, 5, 2, 6, 4, 7, 8 ; double result = average( a ); System.out.println( result ); 11

Example 3: Read a file public static String[] getfileasarray( String filename ) { try { File f = new File(filename); Scanner reader = new Scanner(f); ArrayList<String> content = new ArrayList<String>(); while (reader.hasnextline()) { content.add(reader.nextline()); reader.close(); return((string[])content.toarray(new String[content.size()])); catch (Exception e) { System.out.println("ERROR processing file "+filename); System.out.println(e.getMessage()); return(new String[0]); public static void main(string[] args) { String[] words = getfileasarray("dictionary.txt"); for (String word : words) { System.out.println(word); System.out.println("There were "+words.length+" words!"); 12