Using Two-Dimensional Arrays



Similar documents
JAVA ARRAY EXAMPLE PDF

Using Files as Input/Output in Java 5.0 Applications

Sample CSE8A midterm Multiple Choice (circle one)

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

CS 121 Intro to Programming:Java - Lecture 11 Announcements

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

Basics of Java Programming Input and the Scanner class

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

AP Computer Science File Input with Scanner

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

Arrays in Java. Working with Arrays

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

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

Lecture J - Exceptions

Course Intro Instructor Intro Java Intro, Continued

Scanner sc = new Scanner(System.in); // scanner for the keyboard. Scanner sc = new Scanner(System.in); // scanner for the keyboard

Homework/Program #5 Solutions

Chapter 2 Introduction to Java programming

Object-Oriented Programming in Java

Continuous Integration Part 2

D06 PROGRAMMING with JAVA

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

1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

Iteration CHAPTER 6. Topic Summary

Introduction to Java

Topic 11 Scanner object, conditional execution

Chapter 2. println Versus print. Formatting Output withprintf. System.out.println for console output. console output. Console Input and Output

This explanations are for absolute beginners. Skilled programmers should (and probably will) use more effective approach.

Building Java Programs

Introduction to Object-Oriented Programming

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

Install Java Development Kit (JDK) 1.8

13 File Output and Input

LOOPS CHAPTER CHAPTER GOALS

Part I. Multiple Choice Questions (2 points each):

Chapter 3. Input and output. 3.1 The System class

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

IMDB Data Set Topics: Parsing Input using Scanner class. Atul Prakash

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

MIDTERM 1 REVIEW WRITING CODE POSSIBLE SOLUTION

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Arrays. Introduction. Chapter 7

In this Chapter you ll learn:

Comp 248 Introduction to Programming

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

(Eng. Hayam Reda Seireg) Sheet Java

Two-Dimensional Arrays Summer 2010 Margaret Reid-Miller

The following program is aiming to extract from a simple text file an analysis of the content such as:

Preet raj Core Java and Databases CS4PR. Time Allotted: 3 Hours. Final Exam: Total Possible Points 75

Loops and ArrayLists

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

CS170 Lab 11 Abstract Data Types & Objects

Object Oriented Software Design

Advanced Java Client API

AP Computer Science Static Methods, Strings, User Input

AP Computer Science Java Subset

5.2 Q2 The control variable of a counter-controlled loop should be declared as: a.int. b.float. c.double. d.any of the above. ANS: a. int.

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Threads 1. When writing games you need to do more than one thing at once.

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

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Line-based file processing

Introduction to Java. CS 3: Computer Programming in Java

How to create/avoid memory leak in Java and.net? Venkat Subramaniam

Event-Driven Programming

Week 1: Review of Java Programming Basics

Building Java Programs

CompSci 125 Lecture 08. Chapter 5: Conditional Statements Chapter 4: return Statement

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

CS 112/ Section 02 Hilal Ünal Aslıhan Ekim Merve Özkılınç Notes of March 11, 2008 and March 13, 2008: Pig Latin: add adday. main.

Introduction to Programming

Programming Fundamentals I CS 110, Central Washington University. November 2015

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

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

COSC Introduction to Computer Science I Section A, Summer Question Out of Mark A Total 16. B-1 7 B-2 4 B-3 4 B-4 4 B Total 19

WRITING DATA TO A BINARY FILE

Moving from CS 61A Scheme to CS 61B Java

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

Building Java Programs

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

Scoping (Readings 7.1,7.4,7.6) Parameter passing methods (7.5) Building symbol tables (7.6)

Building a Multi-Threaded Web Server

Java Coding Practices for Improved Application Performance

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:

Data Structures Lecture 1

CS 111 Classes I 1. Software Organization View to this point:

Some Scanner Class Methods

Software Development with UML and Java 2 SDJ I2, Spring 2010

CPLEX Tutorial Handout

Grundlæggende Programmering IT-C, Forår Written exam in Introductory Programming

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

D06 PROGRAMMING with JAVA

Building Java Programs

6.1. Example: A Tip Calculator 6-1

Creating a Simple, Multithreaded Chat System with Java

public static void main(string args[]) { System.out.println( "f(0)=" + f(0));

Third AP Edition. Object-Oriented Programming and Data Structures. Maria Litvin. Gary Litvin. Phillips Academy, Andover, Massachusetts

Transcription:

Using Two-Dimensional Arrays Great news! What used to be the old one-floor Java Motel has just been renovated! The new, five-floor Java Hotel features a free continental breakfast and, at absolutely no charge, a free newspaper delivered to your door every morning. That s a 50-cent value, absolutely free! Speaking of things that are continental, the designers of the new Java Hotel took care to number floors the way people do in France. The ground floor (in French, le rez-de-chaussée ) is the zero floor, the floor above that is the first floor, and so on. Figure B-1 shows the newly renovated hotel. Figure B-1: A big, high-rise hotel. You can think of the hotel as an array with two indices -- a two-dimensional array. You declare the array this way. int guests[][] = new int[5][10]; 1

The guests array has five rows (numbered 0 to 4, inclusive) and ten columns (numbered 0 to 9, inclusive). To register two guests in Room 9 on the first floor, you write guests[1][9] = 2; TechnicalStuff The people who do serious Java like to think of a two-dimensional array as an array of rows (that is, an array of ordinary one-dimensional arrays). With this thinking, the rows of the guests array (above) are denoted guests[0], guests[1], guests[2], guests[3], and guests[4]. For a picture of all this, refer to Figure B-1. A complete program that uses this guest array is shown in Listing B-1. Listing B-1 An array of arrays import static java.lang.system.out; import java.io.file; import java.io.filenotfoundexception; import java.util.scanner; public class ShowGuests { public static void main(string args[]) throws FileNotFoundException { int guests[][] = new int[5][10]; Scanner myscanner = new Scanner(new File("GuestList")); guests[floor][roomnum] = myscanner.nextint(); for (int floor = 4; floor >= 0; floor--) { out.print("floor " + floor + ":"); out.print(" "); out.print(guests[floor][roomnum]); out.println(); out.println(); out.print("room: "); out.print(" "); 2

out.print(roomnum); Figure B-2 shows a run of the code from Listing B-1. The input file, GuestList, looks like the file in Listing 11-1, except that the file for this section s program has 50 lines in it. OnTheWeb You can snare a 50-line GuestList file along with this document s code listings from the book s Web site. Figure B-2: Guest counts. In Listing B-1, notice the primary way you handle a two-dimensional array -- by putting a for loop inside another for loop. For instance, when you read values into the array, you have a room number loop within a floor number loop. Because the roomnum loop is inside the floor loop, the roomnum variable changes faster than the floor variable. In other words, the program prints guest counts for all the rooms on a floor before marching on to the next floor. Remember The outer loop s variable changes slower; the inner loop s variable changes faster. In displaying the hotel s numbers, I could have chosen to start with floor 0 and go up to floor 4. But then the output would have looked like an upsidedown hotel. In the program s output, you want the top floor s numbers to be displayed first. To make this work, I created a loop whose counter goes backwards. for (int floor = 4; floor >= 0; floor--) 3

So notice that the loop s counter starts at 4, goes downward each step of the way, and keeps going down until the counter s value is equal to 0. This section does one better on the stuff from earlier sections. If you can make a two-dimensional array and an array of objects, then why not join these ideas to make a two-dimensional array of objects. Technically, this ends up being an array of arrays of objects. How about that! First you define your two-dimensional array of Room objects. (The declaration of the Room class comes right from Listing 11-5.) Room rooms[][] = new Room[5][10]; Next, you do that all-important step of constructing an object for each component in the array. rooms[floor][roomnum] = new Room(); Then you read values into the array components variables, write values, and so on. A complete program is shown in Listing B-2. Listing B-2 A two-dimensional array of objects import java.io.file; import java.io.filenotfoundexception; import java.util.scanner; import static java.lang.system.out; public class ShowRooms { public static void main(string args[]) throws FileNotFoundException { Room rooms[][] = new Room[5][10]; Scanner myscanner = new Scanner(new File("RoomList")); rooms[floor][roomnum] = new Room(); rooms[floor][roomnum].readroom(myscanner); for (int floor = 4; floor >= 0; floor--) { 4

out.println("floor " + floor + ":"); out.print(" "); rooms[floor][roomnum].writeroom(); out.println(); By the time you re done, the program that uses objects is actually simpler than the code that doesn t use objects. That s because, in writing the code with an array of objects, you re taking advantage of methods that are already written as part of the Room class, such as readroom and writeroom. A run of the code in Listing B-2 displays information about all 50 of the hotel s rooms. Instead of showing you all that stuff, Figure B-3 shows you the first several lines in the run. (You don t need to know about every room in the Java Hotel anyway.) The input to the code in Listing B-2, the RoomList file, looks just like the stuff in Listing 11-7. The only difference is that the RoomList file for this section s code has 150 lines in it. OnTheWeb You can snare a 150-line RoomList file along with this document s code listings from the book s Web site.. Figure B-3: Starting a run of the code from Listing B-2. With all the examples building up to Listing B-2, the code in the listing may be fairly uneventful. The only thing you need to notice is that the line rooms[floor][roomnum] = new Room(); is absolutely, indubitably, 100-percent required. When you accidentally leave off this line (not if you leave off this line, but when you leave off this 5

line ), you get a runtime error message saying java.lang.nullpointerexception. 6