Arrays OBJECTIVES. In this chapter you will learn:

Size: px
Start display at page:

Download "Arrays OBJECTIVES. In this chapter you will learn:"

Transcription

1 7 Arrays Now go, write it before them in a table, and note it in a book. Isaiah 30:8 To go beyond is as wrong as to fall short. Confucius Begin at the beginning, and go on till you come to the end: then stop. Lewis Carroll OBJECTIVES In this chapter you will learn: What arrays are. To use arrays to store data in and retrieve data from lists and tables of values. To declare an array, initialize an array and refer to individual elements of an array. To use the enhanced for statement to iterate through arrays. To pass arrays to methods. To declare and manipulate multidimensional arrays. To write methods that use variable-length argument lists. To read command-line arguments into a program.

2 282 Arrays Chapter7 Sample Output Enter number: Enter number: Enter number: Enter number: has already been entered Enter number: Program Template 1 // Lab 1: Unique.java 2 // Reads in 5 unique numbers. 5 public class Unique 7 // gets 5 unique numbers from the user 8 public void getnumbers() 9 { 10 Scanner input = new Scanner( System.in ); /* Create an array of five elements*/ 13 int count = 0 ; // number of uniques read 1 int entered = 0 ; // number of entered numbers while( entered < numbers.length ) 17 { 18 System.out.print( "Enter number: " ); 19 /* Write code here to retrieve the input from the user */ // validate the input 22 /* Write an if statement that validates the input */ 23 { 2 // flags whether this number already exists 25 boolean containsnumber = false; // increment number of entered numbers 28 entered++; /* Compare the user input to the unique numbers in the array using a for 31 statement. If the number is unique, store new number */ /* add the user input to the array only if the number is not already 3 in the array */ 35 if (!containsnumber ) 3 37 /* Write code to add the number to the array and increment 38 unique items input */ 39 } // end if Fig. L 7.1 Unique.java. (Part 1 of 2.)

3 Chapter 7 Arrays else 1 System.out.printf( "%d has already been entered\n", 2 number ); 3 } // end if else 5 System.out.println( "number must be between 10 and 100" ); 6 7 // print the list of unique values 8 /* Write code to output the contents of the array */ 9 } // end while 50 } // end method getnumbers 51 } // end class Unique Fig. L 7.1 Unique.java. (Part 2 of 2.) 1 // Lab 1: UniqueTest.java 2 // Test application for class Unique 3 public class UniqueTest 7 Unique application = new Unique(); 8 application.getnumbers(); 10 } // end class UniqueTest Fig. L 7.2 UniqueTest.java. Problem-Solving Tips 1. Initialize the integer array numbers to hold five elements. This is the maximum number of values the program must store if all values input are unique. 2. Remember to validate the input and display an error message if the user inputs invalid data. 3. If the number entered is not unique, display a message to the user; otherwise, store the number in the array and display the list of unique numbers entered so far.. If you have any questions as you proceed, ask your lab instructor for assistance. Solution 1 // Lab 1: Unique.java 2 // Reads in 5 unique numbers. 5 public class Unique 7 // gets 5 unique numbers from the user 8 public void getnumbers() 9 { 10 Scanner input = new Scanner( System.in ); int numbers[] = new int[ 5 ]; // list of unique numbers 13 int count = 0 ; // number of uniques read 1 int entered = 0 ; // number of entered numbers 15

4 28 Arrays Chapter7 16 while( entered < numbers.length ) 17 { 18 System.out.print( "Enter number: " ); 19 int number = input.nextint(); // validate the input 22 if ( 10 <= number && number <= 100 ) 23 { 2 // flags whether this number already exists 25 boolean containsnumber = false; // increment number of entered numbers 28 entered++; // compare input number to unique numbers in array 31 for ( int i = 0 ; i < count; i++ ) 32 // if new number is duplicate, set the flag 33 if ( number == numbers[ i ] ) 3 containsnumber = true; // add only if the number is not there already 37 if (!containsnumber ) 38 { 39 numbers[ count ] = number; 0 count++; 1 } // end if 2 else 3 System.out.printf( "%d has already been entered\n", number ); } // end if 5 else 6 System.out.println( "number must be between 10 and 100" ); 7 8 // print the list 9 for ( int i = 0 ; i < count; i++ ) 50 System.out.printf( "%d ", numbers[i] ); System.out.println(); 53 } // end while 5 } // end method getnumbers 55 } // end class Unique 1 // Lab 1: UniqueTest.java 2 // Test application for class Unique 3 public class UniqueTest 7 Unique application = new Unique(); 8 application.getnumbers(); 10 } // end class UniqueTest

5 Chapter 7 Arrays 285 Follow-Up Questions and Activities 1. Modify the program in Lab Exercise 1 to input 30 numbers, each of which is between 10 to 500, inclusive. 1 // Lab 1: Unique.java 2 // Reads in 5 unique numbers. 5 public class Unique 7 // gets 5 unique numbers from the user 8 public void getnumbers() 9 { 10 Scanner input = new Scanner( System.in ); int numbers[] = new int[ 30 ]; // list of unique numbers 13 int count = 0 ; // number of uniques read 1 int entered = 0 ; // number of entered numbers while( entered < numbers.length ) 17 { 18 System.out.print( "Enter number: " ); 19 int number = input.nextint(); // validate the input 22 if ( 10 <= number && number <= 500 ) 23 { 2 // flags whether this number already exists 25 boolean containsnumber = false; // increment number of entered numbers 28 entered++; // compare input number to unique numbers in array 31 for ( int i = 0 ; i < count; i++ ) 32 // if new number is duplicate, set the flag 33 if ( number == numbers[ i ] ) 3 containsnumber = true; // add only if the number is not there already 37 if (!containsnumber ) 38 { 39 numbers[ count ] = number; 0 count++; 1 } // end if 2 else 3 System.out.printf( "%d has already been entered\n", number ); 5 } // end if 6 else 7 System.out.println( "number must be between 10 and 100" ); 8 9 // print the list 50 for ( int i = 0 ; i < count; i++ ) 51 System.out.printf( "%d ", numbers[i] ); 52 System.out.println(); 53 } // end while 5 } // end method getnumbers 55 } // end class Unique

6 286 Arrays Chapter7 1 // Lab 1: UniqueTest.java 2 // Test application for class Unique 3 public class UniqueTest 7 Unique application = new Unique(); 8 application.getnumbers(); 10 } // end class UniqueTest 2. Modify the program in Follow-Up Question 1 to allow the user to enter numbers until the array is full. 1 // Lab 1: Unique.java 2 // Reads in 5 unique numbers. 5 public class Unique 7 // gets 5 unique numbers from the user 8 public void getnumbers() 9 { 10 Scanner input = new Scanner( System.in ); int numbers[] = new int[ 30 ]; // list of unique numbers 13 int count = 0 ; // number of uniques read 1 15 while( count < numbers.length ) 1 17 System.out.print( "Enter number: " ); 18 int number = input.nextint(); // validate the input 21 if ( 10 <= number && number <= 500 ) 22 { 23 // flags whether this number already exists 2 boolean containsnumber = false; // compare input number to unique numbers in array 27 for ( int i = 0 ; i < count; i++ ) 28 // if new number is duplicate, set the flag 29 if ( number == numbers[ i ] ) 30 containsnumber = true; // add only if the number is not there already 33 if (!containsnumber ) 3 35 numbers[ count ] = number; 36 count++; 37 } // end if 38 else 39 System.out.printf( "%d has already been entered\n", 0 number ); 1 } // end if 2 else 3 System.out.println( "number must be between 10 and 100" );

7 Chapter 7 Arrays // print the list 6 for ( int i = 0 ; i < count; i++ ) 7 System.out.printf( "%d ", numbers[i] ); 8 System.out.println(); 9 } // end while 50 } // end method getnumbers 51 } // end class Unique 1 // Lab 1: UniqueTest.java 2 // Test application for class Unique 3 public class UniqueTest 7 Unique application = new Unique(); 8 application.getnumbers(); 10 } // end class UniqueTest 3. Modify your solution to Follow-Up Question 2 to allow the user to enter the size of the array as the application begins execution. 1 // Lab 1: Unique.java 2 // Reads in 5 unique numbers. 5 public class Unique 7 // gets 5 unique numbers from the user 8 public void getnumbers() 9 { 10 Scanner input = new Scanner( System.in ); System.out.print( "How many numbers will you enter? " ); 13 int number = input.nextint(); 1 15 int numbers[] = new int[ number ]; // list of unique numbers 16 int count = 0 ; // number of uniques read while( count < numbers.length ) 19 { 20 System.out.print( "Enter number: " ); 21 number = input.nextint(); // validate the input 2 if ( 10 <= number && number <= 500 ) 25 { 26 // flags whether this number already exists 27 boolean containsnumber = false; 28

8 288 Arrays Chapter7 29 // compare input number to unique numbers in array 30 for ( int i = 0 ; i < count; i++ ) 31 // if new number is duplicate, set the flag 32 if ( number == numbers[ i ] ) 33 containsnumber = true; 3 35 // add only if the number is not there already 36 if (!containsnumber ) 37 { 38 numbers[ count ] = number; 39 count++; 0 } // end if 1 else 2 System.out.printf( "%d has already been entered\n", 3 number ); } // end if 5 else 6 System.out.println( "number must be between 10 and 100" ); 7 8 // print the list 9 for ( int i = 0 ; i < count; i++ ) 50 System.out.printf( "%d ", numbers[i] ); 51 System.out.println(); 52 } // end while 53 } // end method getnumbers 5 } // end class Unique 1 // Lab 1: UniqueTest.java 2 // Test application for class Unique 3 public class UniqueTest 7 Unique application = new Unique(); 8 application.getnumbers(); 10 } // end class UniqueTest

9 Chapter 7 Arrays 297 Debugging Debugging Date: Section: The program in this section does not run properly. Fix all the compilation errors, so that the program will compile successfully. Once the program compiles, compare the output to the sample output, and eliminate any logic errors that exist. The sample output demonstrates what the program s output should be once the program s code is corrected. The file is available at and at Sample Output Enter sales person number (-1 to end): 1 Enter product number: Enter sales amount: 1082 Enter sales person number (-1 to end): 2 Enter product number: 3 Enter sales amount: 998 Enter sales person number (-1 to end): 3 Enter product number: 1 Enter sales amount: 678 Enter sales person number (-1 to end): Enter product number: 1 Enter sales amount: 155 Enter sales person number (-1 to end): -1 Product Salesperson 1 Salesperson 2 Salesperson 3 Salesperson Total Total Broken Code 1 // Debugging Problem Chapter 7: Sales2.java 2 // Program totals sales for salespeople and products. 5 public class Sales2 7 public void calculatesales() 8 { 9 Scanner input = new Scanner( System.in ); 10 // sales array holds data on number of each product sold 11 // by each salesman 12 double sales = new double[ 5 ][ ]; 13 1 System.out.print( "Enter sales person number (-1 to end): " ); 15 int person = input.nextint(); Fig. L 7.5 Sales2.java. (Part 1 of 2.)

10 298 Arrays Chapter7 Debugging while ( person!= -1 ) 18 { 19 System.out.print( "Enter product number: " ); 20 int product = input.next(); 21 System.out.print( "Enter sales amount: " ); 22 double amount = input.nextdouble(); 23 2 // error-check the input 25 if ( person < 1 && person > 5 && 26 product >= 1 && product < 6 && amount >= 0 ) 27 sales[ product - 1 ][ person - 1 ] += amount; 28 else 29 System.out.println( "Invalid input!" ); System.out.print( "Enter sales person number (-1 to end): " ); 32 person = input.nextint(); 33 } // end while 3 35 // total for each salesperson 36 double salespersontotal[][] = new double[ ]; // display the table 39 for ( int column = 0 ; column < ; column++ ) 0 salespersontotal[ column ][ row ] = 0 ; 1 2 System.out.printf( "%7s%1s%1s%1s%1s%10s\n", 3 "Product", "Salesperson 1", "Salesperson 2", "Salesperson 3", "Salesperson ", "Total" ); 5 6 // for each column of each row, print the appropriate 7 // value representing a person's sales of a product 8 for ( int row = 0 ; row < 5 ; row++ ) 9 { 50 double producttotal = 0.0; 51 System.out.printf( "%7d", ( row + 1 ) ); for ( int column = 0 ; column < ; column++ ) { 5 System.out.printf( "%1.2f", sales[ column ][ row ] ); 55 producttotal += sales[ column ][ row ]; 56 salespersontotal[ column ] += sales[ column ][ row ]; 57 } // end for System.out.printf( "%10.2f\n", producttotal ); 60 } // end for System.out.printf( "%7s", "Total" ); 63 6 for ( int column = 0 ; column < ; column++ ) 65 System.out.printf( "%1.2f", salespersontotal[ column ] ); System.out.println(); 68 } // end method calculatesales 69 } // end class Sales2 Fig. L 7.5 Sales2.java. (Part 2 of 2.)

11 Chapter 7 Arrays 299 Debugging 1 // Debugging Problem Chapter 7: Sales2Test.java 2 // Test application for class Sales2 3 public class Sales2Test 7 Sales2 application = new Sales2(); 8 application.calculatesales(); 10 } // end class Sales2Test Fig. L 7.6 Sales2Test.java

12 300 Arrays Chapter7 Debugging Solution 1 // Debugging Problem Chapter 7: Sales2.java 2 // Program totals sales for salespeople and products. 5 public class Sales2 7 public void calculatesales() 8 { 9 Scanner input = new Scanner( System.in ); 10 // sales array holds data on number of each product sold 11 // by each salesman 12 double sales [][] = new double[ 5 ][ ]; 13 1 System.out.print( "Enter sales person number (-1 to end): " ); 15 int person = input.nextint(); while ( person!= -1 ) 18 { 19 System.out.print( "Enter product number: " ); 20 int product = input. nextint(); 21 System.out.print( "Enter sales amount: " ); 22 double amount = input.nextdouble(); 23 2 // error-check the input 25 if ( person >= 1 && person < 5 && 26 product >= 1 && product < 6 && amount >= 0 ) 27 sales[ product - 1 ][ person - 1 ] += amount; 28 else 29 System.out.println( "Invalid input!" ); System.out.print( "Enter sales person number (-1 to end): " ); 32 person = input.nextint(); 33 } // end while 3 35 // total for each salesperson 36 double salespersontotal[] = new double[ ]; // display the table 39 for ( int column = 0 ; column < ; column++ ) 0 salespersontotal[ column ] = 0 ; 1 2 System.out.printf( "%7s%1s%1s%1s%1s%10s\n", 3 "Product", "Salesperson 1", "Salesperson 2", "Salesperson 3", "Salesperson ", "Total" ); 5 6 // for each column of each row, print the appropriate 7 // value representing a person's sales of a product 8 for ( int row = 0 ; row < 5 ; row++ ) 9 { 50 double producttotal = 0.0; 51 System.out.printf( "%7d", ( row + 1 ) ); for ( int column = 0 ; column < ; column++ ) { 5 System.out.printf( "%1.2f", sales[ row ][ column ] ); Fig. L 7.7 Sales2.java

13 Chapter 7 Arrays 301 Debugging 55 producttotal += sales[ row ][ column ]; 56 salespersontotal[ column ] += sales[ row ][ column ]; 57 } // end for System.out.printf( "%10.2f\n", producttotal ); 60 } // end for System.out.printf( "%7s", "Total" ); 63 6 for ( int column = 0 ; column < ; column++ ) 65 System.out.printf( "%1.2f", salespersontotal[ column ] ); System.out.println(); 68 } // end method calculatesales 69 } // end class Sales2 Fig. L 7.7 Sales2.java 1 // Debugging Problem Chapter 7: Sales2Test.java 2 // Test application for class Sales2 3 public class Sales2Test 7 Sales2 application = new Sales2(); 8 application.calculatesales(); 10 } // end class Sales2Test Fig. L 7.8 Sales2Test.java List of Errors Line 12 declaration of two-dimensional array sales is missing the square brackets. Line 20 Use Scanner method nextint to input an integer from the user. Line 25 Tests used to validate value of person have the wrong comparison operators. Line 36 Declaration of array salespersontotal should only have one set of square brackets. Line 0 Array salespersontotal should be indexed only with the value of column. Lines 5 56 Array sales should be indexed with row first, then column.

Assignment Checklist. Prelab Activities. Lab Exercises. Labs Provided by Instructor. Postlab Activities. Section:

Assignment Checklist. Prelab Activities. Lab Exercises. Labs Provided by Instructor. Postlab Activities. Section: 7 Arrays Now go, write it before them in a table, and note it in a book. Isaiah 30:8 To go beyond is as wrong as to fall short. Confucius Begin at the beginning, and go on till you come to the end: then

More information

Arrays OBJECTIVES. In this chapter you will learn:

Arrays OBJECTIVES. In this chapter you will learn: 7 Arrays Now go, write it before them in a table, and note it in a book. Isaiah 30:8 To go beyond is as wrong as to fall short. Confucius Begin at the beginning, and go on till you come to the end: then

More information

Control Statements: Part 1

Control Statements: Part 1 4 Let s all move one place on. Lewis Carroll Control Statements: Part 1 The wheel is come full circle. William Shakespeare How many apples fell on Newton s head before he took the hint! Robert Frost All

More information

Introduction to Java Applications

Introduction to Java Applications 2 Introduction to Java Applications OBJECTIVES In this chapter you will learn: To write simple Java applications. To use input and output statements. Java s primitive types. Basic memory concepts. To use

More information

Instructor: Eng.Omar Al-Nahal

Instructor: Eng.Omar Al-Nahal Faculty of Engineering & Information Technology Software Engineering Department Computer Science [2] Lab 6: Introduction in arrays Declaring and Creating Arrays Multidimensional Arrays Instructor: Eng.Omar

More information

AL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: Text-printing program. CSC 209 JAVA I

AL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: Text-printing program. CSC 209 JAVA I AL GHURAIR UNIVERSITY College of Computing CSC 209 JAVA I week 2- Arithmetic and Decision Making: Equality and Relational Operators Objectives: To use arithmetic operators. The precedence of arithmetic

More information

Programming with Java

Programming with Java Programming with Java Data Types & Input Statement Lecture 04 First stage Software Engineering Dep. Saman M. Omer 2017-2018 Objectives q By the end of this lecture you should be able to : ü Know rules

More information

Introduction to Classes and Objects

Introduction to Classes and Objects 3 Nothing can have value without being an object of utility. Karl Marx Your public servants serve you right. Adlai E. Stevenson Knowing how to answer one who speaks, To reply to one who sends a message.

More information

download instant at

download instant at 2 Introduction to Java Applications: Solutions What s in a name? That which we call a rose By any other name would smell as sweet. William Shakespeare When faced with a decision, I always ask, What would

More information

Welcome1.java // Fig. 2.1: Welcome1.java // Text-printing program.

Welcome1.java // Fig. 2.1: Welcome1.java // Text-printing program. 1 Welcome1.java // Fig. 2.1: Welcome1.java // Text-printing program. public class Welcome1 // main method begins execution of Java application System.out.println( "Welcome to Java Programming!" ); } //

More information

Lecture 9. Assignment. Logical Operations. Logical Operations - Motivation 2/8/18

Lecture 9. Assignment. Logical Operations. Logical Operations - Motivation 2/8/18 Assignment Lecture 9 Logical Operations Formatted Print Printf Increment and decrement Read through 3.9, 3.10 Read 4.1. 4.2, 4.3 Go through checkpoint exercise 4.1 Logical Operations - Motivation Logical

More information

Repetition CSC 121 Fall 2014 Howard Rosenthal

Repetition CSC 121 Fall 2014 Howard Rosenthal Repetition CSC 121 Fall 2014 Howard Rosenthal Lesson Goals Learn the following three repetition methods, their similarities and differences, and how to avoid common errors when using them: while do-while

More information

Assignment 2.4: Loops

Assignment 2.4: Loops Writing Programs that Use the Terminal 0. Writing to the Terminal Assignment 2.4: Loops In this project, we will be sending our answers to the terminal for the user to see. To write numbers and text to

More information

CS111: PROGRAMMING LANGUAGE II

CS111: PROGRAMMING LANGUAGE II CS111: PROGRAMMING LANGUAGE II Computer Science Department Lecture 1(c): Java Basics (II) Lecture Contents Java basics (part II) Conditions Loops Methods Conditions & Branching Conditional Statements A

More information

2.8. Decision Making: Equality and Relational Operators

2.8. Decision Making: Equality and Relational Operators Page 1 of 6 [Page 56] 2.8. Decision Making: Equality and Relational Operators A condition is an expression that can be either true or false. This section introduces a simple version of Java's if statement

More information

Midterm Examination (MTA)

Midterm Examination (MTA) M105: Introduction to Programming with Java Midterm Examination (MTA) Spring 2013 / 2014 Question One: [6 marks] Choose the correct answer and write it on the external answer booklet. 1. Compilers and

More information

Manipulating One-dimensional Arrays

Manipulating One-dimensional Arrays Manipulating One-dimensional Arrays Mitsu Ogihara Department of Computer Science University of Miami 1 / 30 Table of Contents 1 For each 2 Exchanging Values 3 Reversing 2 / 30 For-each iteration For enumerating

More information

THE JAVA FOR STATEMENT

THE JAVA FOR STATEMENT THE JAVA FOR STATEMENT The for statement behaves as a while statement. Its syntax visually emphasizes the code that initializes and updates the loop variables. for ( init; truth value; update ) statement

More information

1. A company has vans to transport goods from factory to various shops. These vans fall into two categories: 50 items 150 items

1. A company has vans to transport goods from factory to various shops. These vans fall into two categories: 50 items 150 items If..Else Statement Exercises 1. A company has vans to transport goods from factory to various shops. These vans fall into two categories: Category Normal Duty Van Heavy Duty Van Capacity 50 items 150 items

More information

COMP 110 Programming Exercise: Simulation of the Game of Craps

COMP 110 Programming Exercise: Simulation of the Game of Craps COMP 110 Programming Exercise: Simulation of the Game of Craps Craps is a game of chance played by rolling two dice for a series of rolls and placing bets on the outcomes. The background on probability,

More information

AP CS Unit 3: Control Structures Notes

AP CS Unit 3: Control Structures Notes AP CS Unit 3: Control Structures Notes The if and if-else Statements. These statements are called control statements because they control whether a particular block of code is executed or not. Some texts

More information

Supplementary Test 1

Supplementary Test 1 Name: Please fill in your Student Number and Name. Student Number : Student Number: University of Cape Town ~ Department of Computer Science Computer Science 1015F ~ 2009 Supplementary Test 1 Question

More information

Object Oriented Programming. Java-Lecture 1

Object Oriented Programming. Java-Lecture 1 Object Oriented Programming Java-Lecture 1 Standard output System.out is known as the standard output object Methods to display text onto the standard output System.out.print prints text onto the screen

More information

Chapter 3 Lab Decision Structures

Chapter 3 Lab Decision Structures Chapter 3 Lab Decision Structures Lab Objectives Be able to construct boolean expressions to evaluate a given condition Be able to compare String objects Be able to use a flag Be able to construct if and

More information

AL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: if Single-Selection Statement CSC 209 JAVA I. week 3- Control Statements: Part I

AL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: if Single-Selection Statement CSC 209 JAVA I. week 3- Control Statements: Part I AL GHURAIR UNIVERSITY College of Computing CSC 209 JAVA I week 3- Control Statements: Part I Objectives: To use the if and if...else selection statements to choose among alternative actions. To use the

More information

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Repe$$on CSC 121 Fall 2015 Howard Rosenthal Repe$$on CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Learn the following three repetition methods, their similarities and differences, and how to avoid common errors when using them: while do-while

More information

CS111: PROGRAMMING LANGUAGE II

CS111: PROGRAMMING LANGUAGE II 1 CS111: PROGRAMMING LANGUAGE II Computer Science Department Lecture 1: Introduction Lecture Contents 2 Course info Why programming?? Why Java?? Write once, run anywhere!! Java basics Input/output Variables

More information

Computer Programming: C++

Computer Programming: C++ The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2003 Muath i.alnabris Computer Programming: C++ Experiment #7 Arrays Part II Passing Array to a Function

More information

Introduction to Classes and Objects

Introduction to Classes and Objects 3 Introduction to Classes and Objects OBJECTIVES In this chapter you will learn: What classes, objects, methods and instance variables are. How to declare a class and use it to create an object. How to

More information

Object Oriented Programming. Java-Lecture 6 - Arrays

Object Oriented Programming. Java-Lecture 6 - Arrays Object Oriented Programming Java-Lecture 6 - Arrays Arrays Arrays are data structures consisting of related data items of the same type In Java arrays are objects -> they are considered reference types

More information

Introduction to Java & Fundamental Data Types

Introduction to Java & Fundamental Data Types Introduction to Java & Fundamental Data Types LECTURER: ATHENA TOUMBOURI How to Create a New Java Project in Eclipse Eclipse is one of the most popular development environments for Java, as it contains

More information

Task #1 The if Statement, Comparing Strings, and Flags

Task #1 The if Statement, Comparing Strings, and Flags Chapter 3 Lab Selection Control Structures Lab Objectives Be able to construct boolean expressions to evaluate a given condition Be able to compare Strings Be able to use a flag Be able to construct if

More information

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Repe$$on CSC 121 Spring 2017 Howard Rosenthal Repe$$on CSC 121 Spring 2017 Howard Rosenthal Lesson Goals Learn the following three repetition structures in Java, their syntax, their similarities and differences, and how to avoid common errors when

More information

Chapter 6: Using Arrays

Chapter 6: Using Arrays Chapter 6: Using Arrays Declaring an Array and Assigning Values to Array Array Elements A list of data items that all have the same data type and the same name Each item is distinguished from the others

More information

Arrays. Eng. Mohammed Abdualal

Arrays. Eng. Mohammed Abdualal Islamic University of Gaza Faculty of Engineering Computer Engineering Department Computer Programming Lab (ECOM 2114) Created by Eng: Mohammed Alokshiya Modified by Eng: Mohammed Abdualal Lab 9 Arrays

More information

1007 Imperative Programming Part II

1007 Imperative Programming Part II Agenda 1007 Imperative Programming Part II We ve seen the basic ideas of sequence, iteration and selection. Now let s look at what else we need to start writing useful programs. Details now start to be

More information

Section 2.2 Your First Program in Java: Printing a Line of Text

Section 2.2 Your First Program in Java: Printing a Line of Text Chapter 2 Introduction to Java Applications Section 2.2 Your First Program in Java: Printing a Line of Text 2.2 Q1: End-of-line comments that should be ignored by the compiler are denoted using a. Two

More information

CS141 Programming Assignment #6

CS141 Programming Assignment #6 CS141 Programming Assignment #6 Due Sunday, Nov 18th. 1) Write a class with methods to do the following output: a) 5 5 5 5 5 4 4 4 4 3 3 3 2 2 1 b) 1 2 3 4 5 4 3 2 1 1 2 3 4 * 4 3 2 1 1 2 3 * * * 3 2 1

More information

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Methods

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Methods WIT COMP1000 Methods Methods Programs can be logically broken down into a set of tasks Example from horoscope assignment:» Get input (month, day) from user» Determine astrological sign based on inputs

More information

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

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements COMP-202 Unit 4: Programming With Iterations CONTENTS: The while and for statements Introduction (1) Suppose we want to write a program to be used in cash registers in stores to compute the amount of money

More information

Introduction to Computer Science Unit 2. Exercises

Introduction to Computer Science Unit 2. Exercises Introduction to Computer Science Unit 2. Exercises Note: Curly brackets { are optional if there is only one statement associated with the if (or ) statement. 1. If the user enters 82, what is 2. If the

More information

Chapter 4: Control structures. Repetition

Chapter 4: Control structures. Repetition Chapter 4: Control structures Repetition Loop Statements After reading and studying this Section, student should be able to Implement repetition control in a program using while statements. Implement repetition

More information

COMP 202. Programming With Iterations. CONTENT: The WHILE, DO and FOR Statements. COMP Loops 1

COMP 202. Programming With Iterations. CONTENT: The WHILE, DO and FOR Statements. COMP Loops 1 COMP 202 Programming With Iterations CONTENT: The WHILE, DO and FOR Statements COMP 202 - Loops 1 Repetition Statements Repetition statements or iteration allow us to execute a statement multiple times

More information

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.

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 4 Lab Loops and Files Lab Objectives Be able to convert an algorithm using control structures into Java Be able to write a while loop Be able to write an do-while loop Be able to write a for loop

More information

Introduction to Software Development (ISD) Week 3

Introduction to Software Development (ISD) Week 3 Introduction to Software Development (ISD) Week 3 Autumn term 2012 Aims of Week 3 To learn about while, for, and do loops To understand and use nested loops To implement programs that read and process

More information

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M Università degli Studi di Bologna Facoltà di Ingegneria Principles, Models, and Applications for Distributed Systems M tutor Isam M. Al Jawarneh, PhD student isam.aljawarneh3@unibo.it Mobile Middleware

More information

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

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments. Java How to Program, 9/e Education, Inc. All Rights Reserved. } Java application programming } Use tools from the JDK to compile and run programs. } Videos at www.deitel.com/books/jhtp9/ Help you get started

More information

5) (4 points) What is the value of the boolean variable equals after the following statement?

5) (4 points) What is the value of the boolean variable equals after the following statement? For problems 1-5, give a short answer to the question. (15 points, ~8 minutes) 1) (4 points) Write four Java statements that declare and initialize the following variables: A) a long integer with the value

More information

Chapter 4: Control structures

Chapter 4: Control structures Chapter 4: Control structures Repetition Loop Statements After reading and studying this Section, student should be able to Implement repetition control in a program using while statements. Implement repetition

More information

AP Computer Science Unit 1. Programs

AP Computer Science Unit 1. Programs AP Computer Science Unit 1. Programs Open DrJava. Under the File menu click on New Java Class and the window to the right should appear. Fill in the information as shown and click OK. This code is generated

More information

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

Tutorial # 4. Q1. Evaluate the logical (Boolean) expression in the following exercise Tutorial # 4 Q1. Evaluate the logical (Boolean) expression in the following exercise 1 int num1 = 3, num2 = 2; (num1 > num2) 2 double hours = 12.8; (hours > 40.2) 3 int funny = 7; (funny!= 1) 4 double

More information

Fundamentals of Programming Data Types & Methods

Fundamentals of Programming Data Types & Methods Fundamentals of Programming Data Types & Methods By Budditha Hettige Overview Summary (Previous Lesson) Java Data types Default values Variables Input data from keyboard Display results Methods Operators

More information

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time Tester vs. Controller Elementary Programming EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG For effective illustrations, code examples will mostly be written in the form of a tester

More information

CS141 Programming Assignment #8

CS141 Programming Assignment #8 CS141 Programming Assignment #8 Due Sunday, April 14th. 1- Write a class with methods to do the following output: a) 5 5 5 5 5 4 4 4 4 3 3 3 2 2 1 b) 1 2 3 4 5 4 3 2 1 1 2 3 4 * 4 3 2 1 1 2 3 * * * 3 2

More information

Introduction to Computer Science Unit 3. Programs

Introduction to Computer Science Unit 3. Programs Introduction to Computer Science Unit 3. Programs This section must be updated to work with repl.it Programs 1 to 4 require you to use the mod, %, operator. 1. Let the user enter an integer. Your program

More information

Elementary Programming

Elementary Programming Elementary Programming EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG Learning Outcomes Learn ingredients of elementary programming: data types [numbers, characters, strings] literal

More information

Motivation of Loops. Loops. The for Loop (1) Learning Outcomes

Motivation of Loops. Loops. The for Loop (1) Learning Outcomes Motivation of Loops Loops EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG We may want to repeat the similar action(s) for a (bounded) number of times. e.g., Print

More information

Motivation of Loops. Loops. The for Loop (1) Learning Outcomes

Motivation of Loops. Loops. The for Loop (1) Learning Outcomes Motivation of Loops Loops EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG We may want to repeat the similar action(s) for a (bounded) number of times. e.g., Print the Hello World message

More information

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

Loops. EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG Loops EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG Learning Outcomes Understand about Loops : Motivation: Repetition of similar actions Two common loops: for

More information

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

Loops. EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG Loops EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG Learning Outcomes Understand about Loops : Motivation: Repetition of similar actions Two common loops: for and while Primitive

More information

Simple Java Programming Constructs 4

Simple Java Programming Constructs 4 Simple Java Programming Constructs 4 Course Map In this module you will learn the basic Java programming constructs, the if and while statements. Introduction Computer Principles and Components Software

More information

Introduction to Java Applications

Introduction to Java Applications 2 What s in a name? that which we call a rose By any other name would smell as sweet. William Shakespeare When faced with a decision, I always ask, What would be the most fun? Peggy Walker Take some more

More information

APCS Semester #1 Final Exam Practice Problems

APCS Semester #1 Final Exam Practice Problems Name: Date: Per: AP Computer Science, Mr. Ferraro APCS Semester #1 Final Exam Practice Problems The problems here are to get you thinking about topics we ve visited thus far in preparation for the semester

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

CS 200 Using Objects. Jim Williams, PhD

CS 200 Using Objects. Jim Williams, PhD CS 200 Using Objects Jim Williams, PhD This Week Notes By Friday Exam Conflict and Accommodations Install Eclipse (version 8) Help Queue Team Lab 2 Chap 2 Programs (P2): Due Thursday Hours Spent Week?

More information

Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays

Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays Outline 13.1 Test-Driving the Salary Survey Application 13.2 Introducing Arrays 13.3 Declaring and Initializing Arrays 13.4 Constructing

More information

CHAPTER 7 ARRAYS: SETS OF SIMILAR DATA ITEMS

CHAPTER 7 ARRAYS: SETS OF SIMILAR DATA ITEMS CHAPTER 7 ARRAYS: SETS OF SIMILAR DATA ITEMS Computers process information and usually they need to process masses of information. In previous chapters we have studied programs that contain a few variables

More information

Lecture 13 & 14. Single Dimensional Arrays. Dr. Martin O Connor CA166

Lecture 13 & 14. Single Dimensional Arrays. Dr. Martin O Connor CA166 Lecture 13 & 14 Single Dimensional Arrays Dr. Martin O Connor CA166 www.computing.dcu.ie/~moconnor Table of Contents Declaring and Instantiating Arrays Accessing Array Elements Writing Methods that Process

More information

Java Coding 3. Over & over again!

Java Coding 3. Over & over again! Java Coding 3 Over & over again! Repetition Java repetition statements while (condition) statement; do statement; while (condition); where for ( init; condition; update) statement; statement is any Java

More information

Practice Midterm 1. Problem Points Score TOTAL 50

Practice Midterm 1. Problem Points Score TOTAL 50 CS 120 Software Design I Spring 2019 Practice Midterm 1 University of Wisconsin - La Crosse February 25 NAME: Do not turn the page until instructed to do so. This booklet contains 10 pages including the

More information

Welcome to the Using Objects lab!

Welcome to the Using Objects lab! Welcome to the Using Objects lab! Learning Outcomes By the end of this lab: 1. Be able to define chapter 3 terms. 2. Describe reference variables and compare with primitive data type variables. 3. Draw

More information

Entry Point of Execution: the main Method. Elementary Programming. Compile Time vs. Run Time. Learning Outcomes

Entry Point of Execution: the main Method. Elementary Programming. Compile Time vs. Run Time. Learning Outcomes Entry Point of Execution: the main Method Elementary Programming EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG For now, all your programming exercises will be defined within the

More information

Computer Science is...

Computer Science is... Computer Science is... Machine Learning Machine learning is the study of computer algorithms that improve automatically through experience. Example: develop adaptive strategies for the control of epileptic

More information

Top-Down Program Development

Top-Down Program Development Top-Down Program Development Top-down development is a way of thinking when you try to solve a programming problem It involves starting with the entire problem, and breaking it down into more manageable

More information

CS 101 Spring 2007 Midterm 2 Name: ID:

CS 101 Spring 2007 Midterm 2 Name:  ID: You only need to write your name and e-mail ID on the first page. This exam is CLOSED text book, closed-notes, closed-calculator, closed-neighbor, etc. Questions are worth different amounts, so be sure

More information

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M Università degli Studi di Bologna Facoltà di Ingegneria Principles, Models, and Applications for Distributed Systems M Control Structures Intro. Sequential execution Statements are normally executed one

More information

Arrays. Weather Problem Array Declaration Accessing Elements Arrays and for Loops Array length field Quick Array Initialization Array Traversals

Arrays. Weather Problem Array Declaration Accessing Elements Arrays and for Loops Array length field Quick Array Initialization Array Traversals Arrays Weather Problem Array Declaration Accessing Elements Arrays and for Loops Array length field Quick Array Initialization Array Traversals Can we solve this problem? Consider the following program

More information

CSCI 136 Data Structures & Advanced Programming. Fall 2018 Instructors Bill Lenhart & Bill Jannen

CSCI 136 Data Structures & Advanced Programming. Fall 2018 Instructors Bill Lenhart & Bill Jannen CSCI 136 Data Structures & Advanced Programming Fall 2018 Instructors Bill Lenhart & Bill Jannen Administrative Details Lab 1 handout is online Prelab (should be completed before lab): Lab 1 design doc

More information

Practice Midterm 1 Answer Key

Practice Midterm 1 Answer Key CS 120 Software Design I Fall 2018 Practice Midterm 1 Answer Key University of Wisconsin - La Crosse Due Date: October 5 NAME: Do not turn the page until instructed to do so. This booklet contains 10 pages

More information

Reviewing for the Midterm Covers chapters 1 to 5, 7 to 9. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Reviewing for the Midterm Covers chapters 1 to 5, 7 to 9. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 Reviewing for the Midterm Covers chapters 1 to 5, 7 to 9 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 2 Things to Review Review the Class Slides: Key Things to Take Away Do you understand

More information

Method OverLoading printf method Arrays Declaring and Using Arrays Arrays of Objects Array as Parameters

Method OverLoading printf method Arrays Declaring and Using Arrays Arrays of Objects Array as Parameters Outline Method OverLoading printf method Arrays Declaring and Using Arrays Arrays of Objects Array as Parameters Variable Length Parameter Lists split() Method from String Class Integer & Double Wrapper

More information

EXCEPTION HANDLING. // code that may throw an exception } catch (ExceptionType parametername) {

EXCEPTION HANDLING. // code that may throw an exception } catch (ExceptionType parametername) { EXCEPTION HANDLING We do our best to ensure program correctness through a rigorous testing and debugging process, but that is not enough. To ensure reliability, we must anticipate conditions that could

More information

Arrays & Classes. Problem Statement and Specifications

Arrays & Classes. Problem Statement and Specifications Arrays & Classes Quick Start Compile step once always make -k baseball8 mkdir labs cd labs Execute step mkdir 8 java Baseball8 cd 8 cp /samples/csc/156/labs/8/*. Submit step emacs Player.java & submit

More information

Introduction to Computer Science Unit 2. Notes

Introduction to Computer Science Unit 2. Notes Introduction to Computer Science Unit 2. Notes Name: Objectives: By the completion of this packet, students should be able to describe the difference between.java and.class files and the JVM. create and

More information

Example: Monte Carlo Simulation 1

Example: Monte Carlo Simulation 1 Example: Monte Carlo Simulation 1 Write a program which conducts a Monte Carlo simulation to estimate π. 1 See https://en.wikipedia.org/wiki/monte_carlo_method. Zheng-Liang Lu Java Programming 133 / 149

More information

Data dependent execution order data dependent control flow

Data dependent execution order data dependent control flow Chapter 5 Data dependent execution order data dependent control flow The method of an object processes data using statements, e.g., for assignment of values to variables and for in- and output. The execution

More information

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

CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types COMP-202 Unit 6: Arrays Introduction (1) Suppose you want to write a program that asks the user to enter the numeric final grades of 350 COMP-202

More information

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

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process Entry Point of Execution: the main Method Elementary Programming EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG For now, all your programming exercises will

More information

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade; Control Statements Control Statements All programs could be written in terms of only one of three control structures: Sequence Structure Selection Structure Repetition Structure Sequence structure The

More information

Section 2.2 Your First Program in Java: Printing a Line of Text

Section 2.2 Your First Program in Java: Printing a Line of Text Chapter 2 Introduction to Java Applications Section 2.2 Your First Program in Java: Printing a Line of Text 2.2 Q1: End-of-line comments that should be ignored by the compiler are denoted using a. Two

More information

Welcome to the Using Objects lab!

Welcome to the Using Objects lab! Welcome to the Using Objects lab! Learning Outcomes By the end of this lab: 1. Be able to define chapter 3 terms. 2. Describe reference variables and compare with primitive data type variables. 3. Draw

More information

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

C212 Early Evaluation Exam Mon Feb Name: Please provide brief (common sense) justifications with your answers below. C212 Early Evaluation Exam Mon Feb 10 2014 Name: Please provide brief (common sense) justifications with your answers below. 1. What is the type (and value) of this expression: 5 * (7 + 4 / 2) 2. What

More information

AP CS A Exam Review Answer Section

AP CS A Exam Review Answer Section AP CS A Exam Review Answer Section TRUE/FALSE 1. ANS: T TOP: Declaring Variables 2. ANS: T TOP: Generating Random Numbers 3. ANS: F TOP: The String Class 4. ANS: F TOP: Method Parameters 5. ANS: F TOP:

More information

CMSC 150 INTRODUCTION TO COMPUTING LAB WEEK 3 STANDARD IO FORMATTING OUTPUT SCANNER REDIRECTING

CMSC 150 INTRODUCTION TO COMPUTING LAB WEEK 3 STANDARD IO FORMATTING OUTPUT SCANNER REDIRECTING CMSC 150 INTRODUCTION TO COMPUTING LAB WEEK 3 STANDARD IO FORMATTING OUTPUT SCANNER REDIRECTING INPUT AND OUTPUT Input devices Keyboard Mouse Hard drive Network Digital camera Microphone Output devices.

More information

Chapter 6 Lab Classes and Objects

Chapter 6 Lab Classes and Objects Lab Objectives Chapter 6 Lab Classes and Objects Be able to declare a new class Be able to write a constructor Be able to write instance methods that return a value Be able to write instance methods that

More information

Chapter 6 Lab Classes and Objects

Chapter 6 Lab Classes and Objects Gaddis_516907_Java 4/10/07 2:10 PM Page 51 Chapter 6 Lab Classes and Objects Objectives Be able to declare a new class Be able to write a constructor Be able to write instance methods that return a value

More information

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Dr. Marenglen Biba (C) 2010 Pearson Education, Inc. All rights reserved. Java application A computer program that executes when you use the java command to launch the Java Virtual Machine

More information

Basic Problem solving Techniques Top Down stepwise refinement If & if else.. While.. Counter controlled and sentinel controlled repetition Usage of

Basic Problem solving Techniques Top Down stepwise refinement If & if else.. While.. Counter controlled and sentinel controlled repetition Usage of Basic Problem solving Techniques Top Down stepwise refinement If & if.. While.. Counter controlled and sentinel controlled repetition Usage of Assignment increment & decrement operators 1 ECE 161 WEEK

More information

This class simulates the Sudoku board. Its important methods are setcell, dorow, docolumn and doblock.

This class simulates the Sudoku board. Its important methods are setcell, dorow, docolumn and doblock. Contents: We studied a code for implementing Sudoku for the major portion of the lecture. In the last 10 minutes, we also looked at how we can call one constructor from another using this (), the use of

More information

Chapter 5 Methods. public class FirstMethod { public static void main(string[] args) { double x= -2.0, y; for (int i = 1; i <= 5; i++ ) { y = f( x );

Chapter 5 Methods. public class FirstMethod { public static void main(string[] args) { double x= -2.0, y; for (int i = 1; i <= 5; i++ ) { y = f( x ); Chapter 5 Methods Sections Pages Review Questions Programming Exercises 5.1 5.11 142 166 1 18 2 22 (evens), 30 Method Example 1. This is of a main() method using a another method, f. public class FirstMethod

More information