Arrays in Java. data in bulk



Similar documents
AP Computer Science Java Mr. Clausen Program 9A, 9B

In this Chapter you ll learn:

You are to simulate the process by making a record of the balls chosen, in the sequence in which they are chosen. Typical output for a run would be:

The resulting tile cannot merge with another tile again in the same move. When a 2048 tile is created, the player wins.

CS170 Lab 11 Abstract Data Types & Objects

Arrays in Java. Working with Arrays

Two-Dimensional Arrays Summer 2010 Margaret Reid-Miller

Mobile App Design Project #1 Java Boot Camp: Design Model for Chutes and Ladders Board Game

Iteration CHAPTER 6. Topic Summary

LAB4 Making Classes and Objects

Moving from CS 61A Scheme to CS 61B Java

1. Use the class definition above to circle and identify the parts of code from the list given in parts a j.

Two-Dimensional Arrays. Multi-dimensional Arrays. Two-Dimensional Array Indexing

Arrays. number: Motivation. Prof. Stewart Weiss. Software Design Lecture Notes Arrays

Arrays. Atul Prakash Readings: Chapter 10, Downey Sun s Java tutorial on Arrays:

System.out.println("\nEnter Product Number 1-5 (0 to stop and view summary) :

Using Files as Input/Output in Java 5.0 Applications

Source Code Translation

Building Java Programs

Install Java Development Kit (JDK) 1.8

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

Massachusetts Institute of Technology 6.005: Elements of Software Construction Fall 2011 Quiz 2 November 21, 2011 SOLUTIONS.

Homework/Program #5 Solutions

VB.NET Programming Fundamentals

J a v a Quiz (Unit 3, Test 0 Practice)

This loop prints out the numbers from 1 through 10 on separate lines. How does it work? Output:

Java Interview Questions and Answers

Introduction to Programming

Cohort: BCA/07B/PT - BCA/06/PT - BCNS/06/FT - BCNS/05/FT - BIS/06/FT - BIS/05/FT - BSE/05/FT - BSE/04/PT-BSE/06/FT

Lecture J - Exceptions

Building Java Programs

CMSC 202H. ArrayList, Multidimensional Arrays

Project 2: Bejeweled

Object-Oriented Programming in Java

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)

Object Oriented Software Design

Introduction to Java

Two-Dimensional Arrays Java Programming 2 Lesson 12

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Event-Driven Programming

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

Debugging. Common Semantic Errors ESE112. Java Library. It is highly unlikely that you will write code that will work on the first go

IRA EXAMPLES. This topic has two examples showing the calculation of the future value an IRA (Individual Retirement Account).

Management Information Systems 260 Web Programming Fall 2006 (CRN: 42459)

Pseudo code Tutorial and Exercises Teacher s Version

More on Objects and Classes

Unit 6. Loop statements

Object Oriented Software Design

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

1.4 Arrays Introduction to Programming in Java: An Interdisciplinary Approach Robert Sedgewick and Kevin Wayne Copyright /6/11 12:33 PM!

8.1. Example: Visualizing Data

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Unix Shell Scripts. Contents. 1 Introduction. Norman Matloff. July 30, Introduction 1. 2 Invoking Shell Scripts 2

Building Java Programs

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Contents. 9-1 Copyright (c) N. Afshartous

Computing Concepts with Java Essentials

What is File Management. Methods for Categorizing Data. Viewing Data on a Computer

Lab Experience 17. Programming Language Translation

Using Two-Dimensional Arrays

Java 6 'th. Concepts INTERNATIONAL STUDENT VERSION. edition

Arrays. Introduction. Chapter 7

The Interface Concept

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

How To Program In Java (Ipt) With A Bean And An Animated Object In A Powerpoint (For A Powerbook)

Invitation to Ezhil : A Tamil Programming Language for Early Computer-Science Education 07/10/13

Topic 11 Scanner object, conditional execution

Example of a Java program

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

AP Computer Science Java Subset

Object Oriented Programming with Java. School of Computer Science University of KwaZulu-Natal

SQL is capable in manipulating relational data SQL is not good for many other tasks

COMPUTER SCIENCE. Paper 1 (THEORY)

Chapter 2 Introduction to Java programming

One Dimension Array: Declaring a fixed-array, if array-name is the name of an array

Laboratory Assignments of OBJECT ORIENTED METHODOLOGY & PROGRAMMING (USING C++) [IT 553]

arrays C Programming Language - Arrays

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

WA2099 Introduction to Java using RAD 8.0 EVALUATION ONLY. Student Labs. Web Age Solutions Inc.

Sample CSE8A midterm Multiple Choice (circle one)

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

Chapter 1 Java Program Design and Development

Summit Public Schools Summit, New Jersey Grade Level / Content Area: Mathematics Length of Course: 1 Academic Year Curriculum: AP Computer Science A

Java from a C perspective. Plan

INTRODUCTION TO COMPUTER PROGRAMMING. Richard Pierse. Class 7: Object-Oriented Programming. Introduction

Part 3: GridWorld Classes and Interfaces

USING METHODS PROGRAMMING EXAMPLES

Problem 1. CS 61b Summer 2005 Homework #2 Due July 5th at the beginning of class

Visual Basic Programming. An Introduction

To Java SE 8, and Beyond (Plan B)

CmpSci 187: Programming with Data Structures Spring 2015

Creating a 2D Game Engine for Android OS. Introduction

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c

10 Java API, Exceptions, and Collections

DATA STRUCTURES USING C

Some Scanner Class Methods

Java (12 Weeks) Introduction to Java Programming Language

Transcription:

Arrays in Java data in bulk

Array Homogeneous collection of elements all same data type can be simple type or object type Each element is accessible via its index (random access) Arrays are, loosely speaking, objects require initialization with the new operator possess an instance variable (length)

Array declaration & initialization The syntax for array declaration is: datatype [] name; Examples: int [] numlist; String [] names; Object stuff []; // variant syntax still allowed We initialize an array with new, specifying the length; syntax: name = new datatype[size]; e.g. names = new String[100]; Declaration and initialization are often combined: int [] numlist = new int[1000];

Quick check: use the space below to write code that declares & initializes an array of 100 ints to random values

Populating an array Simple type arrays are often populated using a simple count-controlled loop: Random rg = new Random(); for (int x = 0; x < numlist.length; x++) numlist[x] = rg.nextint(5000); Relatively small arrays can also be initialized at declaration: String [] colors = { red, green, blue };

Iterating over an array Recent versions of Java have incorporated a new style of for loop, specifically for stepping through arrays Syntax: for (data type item: arrayname) { } // use item here instead of arrayname[x]

Quick Check re-write loop on the double [] values = new double [100] for (int x=0; x<values.length; x++) values[x] = x *.5; left using new style

Arrays of objects The new operator that creates an array of objects creates an empty array The new operator and a constructor are required to populate the array with objects The next slide contains excerpts from a program containing several arrays of objects The program displays randomly-selected images in a slide show

Variable declarations private Icon [] imagearray; // array of pictures for slide show private int index = 0; // index of next image random # private Container win; // content pane of frame for image display private JLabel pic; // image gets embedded here for display private Timer t; // object that controls slide change private Random rg; // random # generator private String prefix; // holds name of image directory private String [] filenames; // holds names of image files private File picdir; // used to obtain list of file names private int numpix; // used to size imagearray

Constructor excerpts prefix = new String ("C:\\Documents and Settings\\cshelle\\My Documents\\My Pictures"); picdir = new File(prefix); // sets up directory object refers to specified folder filenames = picdir.list(); // returns array of Strings names of files in the My Pictures folder numpix = filenames.length; // number of image files in the folder imagearray = new ImageIcon[numPix]; // array of images to display will be all images in folder

Constructor excerpts, continued for(int x=0; x<imagearray.length; x++) imagearray[x] = new ImageIcon(prefix+"\\"+fileNames[x]); // populate imagearray with pictures from folder rg = new Random(); // initialize new random # generator pic = new JLabel(imageArray[rg.nextInt(numPix)]); // grab first random image, embed in JLabel object win.add(pic); // put the picture in the window t = new Timer(3000, this); t.start(); // initialize & start Timer object

Arrays & methods An array can be either a parameter to or return value from a method array parameter: void fillarray (int [] list) array return value: int [] createlist (int size) examples of calls to these methods: int [] example = createlist(100); fillarray(example);

Arrays & methods An important key point to remember when working with array arguments: you need to pass the array reference (the name of your array variable) when a parameter calls for an array argument No other notation is necessary, and would likely result in a syntax or logic error

Multi-dimensional arrays The arrays described thus far have been of the one-dimensional variety A multidimensional array is an array of arrays; we describe a two-dimensional array as having rows and columns Each row is an array of columns There are 2 indexes; the first indicates the row position, the second the column position

Declaring & using a 2D array Declaration: datatype [][] name; Initialization: name = new datatype[# rows][# columns]; note that if datatype is an object type, you still need to call the constructor for each object, just as you did for the 1-dimensional version 2D array is typically processed using nested loops

Example import java.util.*; public class NumTableDemo { private int[][]table; private Random rg; public NumTableDemo (int size) { rg = new Random(); table = new int[size][size]; for (int x=0; x < table.length; x++) for (int y=0; y < table[x].length; y++) table[x][y] = rg.nextint(size * 2) + 1; }

Quick check write a method that prints out the table, nicely formatted

Finding sums of rows public int[] sumrows() { int [] rowsums = new int [table.length]; for (int x=0; x < table.length; x++) { int sum = 0; for (int y=0; y < table[x].length; y++) sum = sum + table[x][y]; rowsums[x] = sum; } return rowsums; }

Finding sums of columns public int[] sumcolumns() { int[] colsums = new int [table.length]; for (int x=0; x<table.length; x++) { int sum = 0; for (int y=0; y<table.length; y++) sum = sum + table[y][x]; colsums[x] = sum; } return colsums; }

A main method for testing public static void main (String [] args) { NumTableDemo demo = new NumTableDemo(5); demo.showtable(); int [] rowtotals = demo.sumrows(); System.out.println("Sum of rows:"); for (int x=0; x<rowtotals.length; x++) System.out.println(rowTotals[x]); System.out.println ("Sums of columns:"); int [] coltotals = demo.sumcolumns(); for (int x=0; x<coltotals.length; x++) System.out.printf("%3d", coltotals[x]); } } // end of class

Quick check: write a method that returns the average of values in rows or columns

Class exercise: Sudoku I have provided the beginning of a class for playing Sudoku Several methods need to be added: a method to process user input a method that checks for rule violations a method or set of methods that allows users to set up new games Work in groups of 2 or 3