Declaring and ini,alizing 2D arrays

Similar documents
Learning objec-ves. Declaring and ini-alizing 2D arrays. Prin-ng 2D arrays. Using 2D arrays Decomposi-on of a solu-on into objects and methods

CS 231 Data Structures and Algorithms Fall Arrays Lecture 07 - September 19, Prof. Zadia Codabux

Learning objec<ves. Classes, Objects, and Methods. Problem Decomposi<on. Problem Decomposi<on (cont d)

method method public class Temperature { public static void main(string[] args) { // your code here } new

CS201 - Assignment 3, Part 2 Due: Wednesday March 5, at the beginning of class

Methods. Methods. Mysteries Revealed

Arrays. Loops + arrays: challenge problem. Arrays (II) An array is a set of variables of the same type accessed by their index.

Array Basics: Outline

Array Basics: Outline

Two Dimensional Arrays

Loops! Step- by- step. An Example while Loop. Flow of Control: Loops (Savitch, Chapter 4)

APCS Semester #1 Final Exam Practice Problems

Collections. Collections Collection types Collection wrappers Composite classes revisited Collection classes Hashtables Enumerations

Remedial Java - Excep0ons 3/09/17. (remedial) Java. Jars. Anastasia Bezerianos 1

Slide 1 CS 170 Java Programming 1 Multidimensional Arrays Duration: 00:00:39 Advance mode: Auto

CS 177 Recitation. Week 8 Methods

Array. Array Declaration:

Question 1 [20 points]

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

Searching and Sorting (Savitch, Chapter 7.4)

Introduction to Object-Oriented Programming

What is an algorithm?

Programming Languages and Techniques (CIS120)

Collections. Collections. Collections - Arrays. Collections - Arrays

Arrays. COMS W1007 Introduction to Computer Science. Christopher Conway 10 June 2003

COSC 111: Computer Programming I. Dr. Bowen Hui University of Bri>sh Columbia Okanagan

Finding Determinants Through Programming

13 th Windsor Regional Secondary School Computer Programming Competition

Chapter 8 Multi-Dimensional Arrays

Give one example where you might wish to use a three dimensional array

Java Programming. What is a program? Programs Recipes. Programs as Recipes 8/16/12. Pancakes In one bowl. mix: 1½ cup flour

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved

Array Basics: Outline

Computer Programming, I. Laboratory Manual. Experiment #9. Multi-Dimensional Arrays

Computer Programming: C++

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

An array is a collection of data that holds fixed number of values of same type. It is also known as a set. An array is a data type.

CSE 142 Su01 Final Exam Sample Solution page 1 of 7

CS159 Midterm #1 Review

Arrays. Chapter 7 Part 3 Multi-Dimensional Arrays

We have written lots of code so far It has all been inside of the main() method What about a big program? The main() method is going to get really

Last Class. More on loops break continue A bit on arrays

Array Basics: Outline. Creating and Accessing Arrays. Creating and Accessing Arrays. Arrays (Savitch, Chapter 7)

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

Computer Science 252 Problem Solving with Java The College of Saint Rose Spring Topic Notes: Collections

Last Class. Introduction to arrays Array indices Initializer lists Making an array when you don't know how many values are in it

Assertions, pre/postconditions

Lecture 17. For Array Class Shenanigans

Computer Programming for Engineering Applica4ons. Intro to Programming 10/22/13 1 ECE 175. Mul4- dimensional Arrays

Classes. Classes as Code Libraries. Classes as Data Structures

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

CS Programming I: ArrayList

To keep track of this new wrinkle we need some new variables at the Class level:

Notes - Recursion. A geeky definition of recursion is as follows: Recursion see Recursion.

Object Oriented Programming. Java-Lecture 6 - Arrays

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.

CS S-08 Arrays and Midterm Review 1

Design and Debug: Essen.al Concepts CS 16: Solving Problems with Computers I Lecture #8

This exam is open book. Each question is worth 3 points.

Java Review. Fundamentals of Computer Science

Controls Structure for Repetition

How to declare an array in C?

AP Computer Science Lists The Array type

Classes and Objects 3/28/2017. How can multiple methods within a Java class read and write the same variable?

Pointers. A pointer is simply a reference to a variable/object. Compilers automatically generate code to store/retrieve variables from memory

Lab 1: Silver Dollar Game 1 CSCI 2101B Fall 2018

CSE 331 Final Exam 12/9/13

Java Foundations. 7-2 Instantiating Objects. Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Lecture 17. Instructor: Craig Duckett. Passing & Returning Arrays

COSC 111: Computer Programming I. Dr. Bowen Hui University of Bri>sh Columbia Okanagan

Lecture 13: Two- Dimensional Arrays

Tic Tac Toe Game! Day 8

Introduction. Data in a table or a matrix can be represented using a two-dimensional array. For example:

class objects instances Fields Constructors Methods static

CS 201 Advanced Object-Oriented Programming Lab 6 - Sudoku, Part 2 Due: March 10/11, 11:30 PM

St. Edmund Preparatory High School Brooklyn, NY

Java Programming Unit 7. Error Handling. Collec7ons

Data dependent execution order data dependent control flow

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

Lesson 10: Quiz #1 and Getting User Input (W03D2)

Introduction to the Java Basics: Control Flow Statements

CS 101 Spring 2007 Midterm 2 Name: ID:

This Week s Agenda (Part A) CS121: Computer Programming I. The Games People Play. Data Types & Structures. The Array in Java.

CS61B Lecture #35. [The Lecture #32 notes covered lectures #33 and #34.] Today: Enumerated types, backtracking searches, game trees.

18-Dec-09. Exercise #7, Joongle. Background. Sequential search. Consider the following text: Search for the word near

Write for your audience

8/25/17. Demo: Create application. CS2110, Recita.on 1. Arguments to method main, Packages, Wrapper Classes, Characters, Strings.

YEAHtzee. Tuesday Nov Aamnah Khalid and Peter Maldonado

CP122 CS I. Iteration

Welcome to CSSE 220. We are excited that you are here:

AP Computer Science Unit 1. Writing Programs Using BlueJ

Declaring Array Variable

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

Objec,ves. Review: Object-Oriented Programming. Object-oriented programming in Java. What is OO programming? Benefits?

Unit 5: More on Classes/Objects Notes

Multidimensional Arrays. CSE 114, Computer Science 1 Stony Brook University

Introduction to Programming Using Java (98-388)

More About Classes CS 1025 Computer Science Fundamentals I Stephen M. Watt University of Western Ontario

CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays

CS106A, Stanford Handout #18. Writing a Class

Transcription:

Declaring and ini,alizing 2D arrays 4 2D Arrays (Savitch, Chapter 7.5) TOPICS Multidimensional Arrays 2D Array Allocation 2D Array Initialization TicTacToe Game // se2ng up a 2D array final int M=3, N=4; int [][] matrix = new int [M][N]; 3 for(int i=0; i<m; i++) { for (int j=0; j<n; j++) { matrix[i][j] = filescanner.nextint(); 0,0 0,1 0,2 0,3 1,0 1,1 1,2 1,3 CS 160, Fall Semester 2014 2 Prin,ng 2D arrays // prin,ng from a 2D array final int M=100, N=200; int [][] matrix = new int [M][N]; for(int i=0; i<m; i++) { for (int j=0; j<n; j++) { System.out.print(matrix[i][j] + ); System.out.println(); CS 160, Fall Semester 2014 3 Adding two matrices // se2ng up a 2D array m1 m2 0,0 0,1 0,2 0,3 0,0 0,1 0,2 0,3 final int M=100, N=200; int [][] m1 = new int [M][N]; int [][] m2 = new int [M][N]; 1,0 1,1 1,2 1,3 + 1,0 1,1 1,2 1,3 // First write code to ini,alize the matrices m1 and m2 as an exercise int [][] m3 = new int[m][n]; for(int i=0; i<m; i++) { for (int j=0; j<n; j++) { m3[i][j] = m1[i][j] + m2[i][j]; CS 160, Fall Semester 2014 + m3 0,0 0,1 0,2 0,3 1,0 1,1 1,2 1,3 The numbers in each cell represent the indices 4 1

More on 2D arrays Review (Java) int[][] matrix = new int[3][4]; What is matrix.length? It is 3 What is matrix[0].length? It is 4 So is matrix[1].length, matrix[2].length, and matrix[3].length You can access a par,cular row using matrix[i] where i refers to the row number between 0 and 2 Each row is a one- dimensional array You cannot access a column like that L Exercises: Write code that subtracts one matrix from another Write code that transposes the given matrix CS 160, Fall Semester 2014 5 Assignments & expressions Sequen,al control: if & switch Looping control: while, for, do Organiza,on: classes & methods Tools: Eclipse & debugging Why? So you can program CS 160, Fall Semester 2014 6 Programming Challenge Problem but programming isn t about syntax You can program in many languages Programming is about problem solving Problem defini,on/refinement Problem decomposi,on Managing complexity So here is a problem to be worked through together: Write a person versus computer TicTacToe game. CS 160, Fall Semester 2014 7 CS 160, Fall Semester 2014 8 2

Challenge Problem Write a TicTacToe game Machine goes first, plays X Print the board before every user move User plays O, specifies moves by coordinate 0..2, 0..2. Machine selects random, legal moves Program knows when game is over Game board State Player moves User I/O Decomposi,on Computer moves Select random, legal moves Manage game Alternate turns un,l end CS 160, Fall Semester 2014 9 CS 160, Fall Semester 2014 10 Further Decomposi,on Code (Part 1a) Game board Maintain board state 2D array makes sense Mark board square Add an X or O at row, col Check that row, col are empty Print en,re board Show the state of the board Detect game over Focusing on the game state: Board state needed by mul,ple subtasks Good candidate for an instance variable Ini,alize the board : method Mark a square : method Print the board : method Detect game over : methods CS 160, Fall Semester 2014 11 CS 160, Fall Semester 2014 12 3

Public vs Private What is the difference between public & private variables/methods? If something is public, it can be accessed by other objects Think of the String object If it s length() method weren t public, you couldn t use it! If something is private, only methods of the same class can access it Note that if something is public, it can be changed at any point (more error checking!) General rule: top- level methods should be public, everything else should be private CS 160, Fall Semester 2014 13 Code (Part 1b) marksquare() & printboard() are straighoorward Note error checking, only valid moves allowed print just iterates the 2D array What about gameover()? When is a game of,c- tac- toe over? When there is a row of X s or O s or a column or a diagonal or the board is full (,e game) So may require decomposi,on Leading to more methods CS 160, Fall Semester 2014 14 Stop! Do not pass go or collect $200 Code (Part 2) DO NOT write the whole program at all once Too hard to debug that way Test each piece separately Write a temporary main func,on Have it ini,alize the board, mark a square, print the result. Does it work? Have it test end of game scenarios too. Then comment out the test code It s not part of the final product. Think of it like scaffolding OK, now we need to get moves from the user Print a prompt Read in coordinates Call marksquare() Probably doesn t need further decomposi,on But does need to be tested! CS 160, Fall Semester 2014 15 CS 160, Fall Semester 2014 16 4

Code (Part 3) Machine move: picked at random Java has a Random class Generates a stream of pseudo- random numbers Pick a row and col at random Between 0 and 2 Check if legal. If not, pick another What will happen if board is full? Don t forget tes,ng. Ini,aliza,on Problem: which method allocates the board? How about Scanner and Random? We want instance variables ini,alized before any other method is called But we haven t decided which method will be called first Even if we had, might change when the code is modified Solu,on: A constructor is a method that is called by new when an object is created. CS 160, Fall Semester 2014 17 CS 160, Fall Semester 2014 18 Constructors Code (Part 4) The syntax for constructors is unique Constructors take parameters, but they never return a value The constructor name is always the same as the class name The default constructor has no parameters, but we can add them The constructor is generally used to ini,alize class instance variables Now we ve done everything but play the game! The game is the main func,on What should happen when the class is executed Hence, public sta,c void main(string[] args) The game depends on instance variables, so main needs to instan,ate TicTacToe CS 160, Fall Semester 2014 19 CS 160, Fall Semester 2014 20 5

Eclipse Demo Write the program for TicTacToe Will be posted on the course website CS 160, Fall Semester 2014 21 6