Tutorial 12. Exercise 1: Exercise 2: CSC111 Computer Programming I

Similar documents
Birkbeck (University of London) Software and Programming 1 In-class Test Mar Answer ALL Questions

Web-CAT submission URL: CAT.woa/wa/assignments/eclipse

while (/* array size less than 1*/){ System.out.print("Number of students is invalid. Enter" + "number of students: "); /* read array size again */

CAT.woa/wa/assignments/eclipse

Java Classes: Random, Character A C S L E C T U R E 6

CMSC 132: Object-Oriented Programming II. Inheritance

CSCI 136 Data Structures & Advanced Programming. Lecture 3 Fall 2017 Instructors: Bill & Bill

Birkbeck (University of London) Software and Programming 1 In-class Test Mar 2018

Tutorial 11. Exercise 1: CSC111 Computer Programming I. A. Write a code snippet to define the following arrays:

AP COMPUTER SCIENCE A

Arrays. Eng. Mohammed Abdualal

Arrays. Here is the generic syntax for an array declaration: type[] <var_name>; Here's an example: int[] numbers;

1 Short Answer (10 Points Each)

Last Class. While loops Infinite loops Loop counters Iterations

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

Instance Method Development Demo

CS 1331 Exam 1. Fall Failure to properly fill in the information on this page will result in a deduction of up to 5 points from your exam score.

Getter and Setter Methods

Exam 2. Programming I (CPCS 202) Instructor: M. G. Abbas Malik. Total Marks: 40 Obtained Marks:

Practice Problems: Instance methods

1) Consider the following code segment, applied to list, an ArrayList of Integer values.

Tutorial 03. Exercise 1: CSC111 Computer Programming I

1.00 Introduction to Computers and Engineering Problem Solving. Quiz 1 March 7, 2003

1 Short Answer (15 Points Each)

Types in Java. 8 Primitive Types. What if we want to store lots of items e.g. midsem marks?

Object Oriented Programming. Java-Lecture 6 - Arrays

H212 Introduction to Software Systems Honors

AP Computer Science Unit 1. Programs

CSE 1223: Exam II Autumn 2016

Passing Array to Methods

- Aggregation - UML diagram - Self-Referential Classes - Generisity

PASS4TEST IT 인증시험덤프전문사이트

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

CSEN202: Introduction to Computer Science Spring Semester 2017 Midterm Exam

SPRING 13 CS 0007 FINAL EXAM V2 (Roberts) Your Name: A pt each. B pt each. C pt each. D or 2 pts each

CS 1331 Exam 1 ANSWER KEY

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University

Lab Exercise 1. Objectives: Part 1. Introduction

AP CS Unit 7: Arrays Exercises

CS111: PROGRAMMING LANGUAGE II

Objects and Classes User-defined classes, creating objects, accessing object s members

Day 3. COMP 1006/1406A Summer M. Jason Hinek Carleton University

Objectives: Lab Exercise 1 Part 1. Sample Run. Part 2

First Exam Computer Programming 326 Dr. St. John Lehman College City University of New York Thursday, 7 October 2010

CSC141, Computer Science I, Instructor: Dr. Zhen Jiang, Test 2

Instructions. Objectives:

Data Structures Brett Bernstein

University of Cape Town ~ Department of Computer Science. Computer Science 1015F ~ 2007

Computer Science is...

Control Structures: if and while A C S L E C T U R E 4

Oct Decision Structures cont d

Introduction To Data Structures

Software and Programming 1

Assignment 8B SOLUTIONS

CS 113 MIDTERM EXAM 2 SPRING 2013

CSC 1051 Algorithms and Data Structures I. Final Examination May 2, Name:

Objects and Classes. 1 Creating Classes and Objects. CSCI-UA 101 Objects and Classes

Example: Computing prime numbers

Ahmadu Bello University Department of Mathematics First Semester Examinations June 2014 COSC211: Introduction to Object Oriented Programming I

Computer Programming, I. Laboratory Manual. Final Exam Solution

COE 212 Engineering Programming. Welcome to Exam I Tuesday November 11, 2014

COMP-202B - Introduction to Computing I (Winter 2011) - All Sections Example Questions for In-Class Quiz

Functions. Arash Rafiey. September 26, 2017

1. Which of the following is the correct expression of character 4? a. 4 b. "4" c. '\0004' d. '4'

Introduction to Computer Science Unit 2. Exercises

MIDTERM REVIEW. midterminformation.htm

CSC 1051 Data Structures and Algorithms I

Lists. Arrays. CPSC 233: Introduction to Data Structures, Lists 1. James Tam. James Tam

University of Cape Town ~ Department of Computer Science Computer Science 1015F ~ Test 2. Question Max Mark Internal External

Table of Contents Date(s) Title/Topic Page #s. Chapter 4: Writing Classes 4.1 Objects Revisited

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

Choose 3 of the 1 st 4 questions (#'s 1 through 4) to complete. Each question is worth 12 points.

It is a constructor and is called using the new statement, for example, MyStuff m = new MyStuff();

Midterm Examination (MTA)

Objectives of the lesson

CS Week 13. Jim Williams, PhD

Chapter 5: Classes and Objects in Depth. Introduction to methods

CS 455 Midterm Exam 1 Fall 2013 [Bono] Wednesday, Oct. 2, 2013

(A) 99 ** (B) 100 (C) 101 (D) 100 initial integers plus any additional integers required during program execution

COE 212 Engineering Programming. Welcome to the Final Exam Tuesday December 15, 2015

Introduction to Computer Science Unit 2. Notes

Chapter 8 Multi-Dimensional Arrays

CSCI 136 Data Structures & Advanced Programming. Lecture 3 Fall 2018 Instructors: Bill & Bill

BİLGE KÖROĞLU. Lecture Notes (May 2 4, 2007) METHOD DECOMPOSITION and ARRAYS

Fundamentals of Programming Data Types & Methods

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

Assignment 1 due Monday at 11:59pm

Midterm Practice Problems - answer key Answers appear in boldface.

Final Exam Practice. Partial credit will be awarded.

H212 Introduction to Software Systems Honors

Lecture 3. Lecture

University of Massachusetts Amherst, Electrical and Computer Engineering

3. Convert 2E from hexadecimal to decimal. 4. Convert from binary to hexadecimal

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

CIS 110 Introduction to Computer Programming. 12 February 2013 Midterm. Answer Key

SAMPLESAMPLESAMPLESAMPLESAMPLESAMPLESAMPLESAMPLESAMPLESAMPLE SAMPLE CSE21

CS170 Introduction to Computer Science Midterm 2

1. Expressions - 1 point each. -1 for missing or extra " OR.0. differences in capitalization of true and false okay. No limit on points off.

Esc101 Mid Semester Exam - II

Question 1: (5 marks) Give the output of the following program if the input from the keyboard is:

Transcription:

College of Computer and Information Sciences CSC111 Computer Programming I Exercise 1: Tutorial 12 Arrays: A. Write a method add that receives an array of integers arr, the number of the elements in the array arr and an integer n. It then adds the integer n to the array arr if the number of elements in the array is less than its size. Method add uses another method find that checks if the integer n is in the array or not. Method add returns false if n can not be added or is already in arr. B. Write a method flipcoin that receives an array of boolean flips and the number of coin flips so far. The method randomly flips a coin by calling method nextboolean of class java.util.random and stores the new flip in array flips if array is not full. C. Write a method deletetweet that receives your tweets, their number and a tweet that you would like to remove. The method then searches for the tweet and delete it from your twitter history. If tweet was not found, an error message is reported. D. Write a method findmove that receives the history of moves made by a robot, the number of moves so far and a move. A move consists of two parts dx and dy which represent the amount of units traveled on x and y axis. The history is stored in two arrays one for each axis. The method looks up the move and returns its index in the two arrays otherwise it returns 1. Exercise 2: Suppose we have the following class Customer: public class Customer { private int id; private String name; private double totalsales; // Constructors, Setters, and Getters are here public void addsales(double price) { public boolean equalsc(customer c) { totalsales = totalsales + price; return (this.id == c.id && this.name.equalsignorecase(c.name) && this.totalsales == c.totalsales); A. Passing an array element as an argument: In a different class, suppose you created an array of objects of type Customer and an aarray of type double to store prices as follows:

Customer[] cmr = new Customer[3]; double[] prices = new double[3]; // Create objects for 1st and 2nd elements of cmr: cmr[0] = new Customer(1, "Ahmad", 0); cmr[1] = new Customer(2, "Saleh", 0); prices[0] = 10.0; prices[1] = 20.0; prices[2] = 30.0; 1. Write a code to call the method equalsc to compare the 1st element and the 2nd element of the array cmr. 2. Write a code to call the method addsales from the 1st customer. We want to add (send) the 2nd element from the array prices. B. Dealing with runtime errors: Suppose we run this code fragment: int id = cmr[2].getid(); What will happen? 1. Nothing, it will return the ID of the 3rd customer to be assigned to the variable id. 2. There is a compilation error. 3. There is a runtime error. C. Suppose we run this code fragment: for (int i = 0; i <= cmr.length; i++) System.out.print("Name " + i + " = " + cmr[i].getname()); What will be the output, if any? 1. Name0 = Ahmad Name1 = Saleh Name2 = Any Name 2. There is a compilation error. 3. There is a runtime error. 1

Exercise 3 Suppose we have the UML diagram for these two classes: import java.util.scanner; public class Tutorial { private String name; private int id; private double[] grades; private static final int DEFAULT_SIZE = 10; public Tutorial() { name = "no name"; id = 1; grades = new double[default_size]; public Tutorial(String newname,int newid,double[] newgrades) { name = newname; id = newid; grades = newgrades; public String getname() { return name; public void setname(string name) { this.name = name; public int getid() { return id; public void setid(int id) { this.id = id; public double[] getgrades() { return grades; public void setgrades(double[] grades) {this.grades = grades; //The rest of the methods will be here, // and they are discussed in the next pages. The method fillgrades() steps through the grades array of a certain student. The values are read from the user. public void fillgrades(){ Scanner kb = new Scanner(System.in); for(int i = 0; i < grades.length; i++) grades[i] = kb.nextdouble(); 2

The method addbonus(double bonusamount) will add a double value to all the elements of the grades array of the current student. The value added is received using the parameter bonusamount. After it finished adding the bonus to all the grades, the method returns the whole array to the invoker. Here is the method s code: public double[] addbonus(double bonusamount) { for (int i=0; i < grades.length; i++) grades[i] = grades[i] + bonusamount; The method reversegradesarray(double[] gradestobereversed) will reverse the elements of the grades array. The reversing process is done as following (grades array has n elements): 1. The 1st element is swapped with the last element (n 1). 2. The 2nd element is swapped with the element (n 2). 3. The 3rd element is swapped with the element (n 3). 4. And so on public void reversegradesarray(double[] gradestobereversed) { double temp; int n = gradestobereversed.length; for (int i = 0; i < n/2; i++) { temp = gradestobereversed[i]; gradestobereversed[i] = gradestobereversed[(n 1) i]; gradestobereversed[(n 1) i] = temp; Method foundid(tutorial[] s, int id, int lastindexreached) will: 1. look for a student ID and return true if the student was found. 2. help us to avoid adding an existing ID, since IDs must be unique. 3. receive a student information array, which is an array of class Tutorial type 4. receive the ID of the student we are looking for 5. receive the last index reached so we look for previous elements only! public static boolean foundid(tutorial[] s, int id, int lastindexreached) { boolean found = false; for(int i = 0; i < lastindexreached; i++) if(s[i].getid() == id) found = true; return found; Method findindexbyid(tutorial[ ] s, int id) will: 1. look for the location of the student who s ID is id in the student information array. 2. return the location (index) if ID is found, and 1 if not found. public static int findindexbyid(tutorial[] s, int id) { for(int i = 0; i < s.length; i++) if(s[i].getid() == id) return i; return 1; Method reversestudentinfoarray(tutorial[] StudentInfoToBeReversed) will: 3

1. reverse the elements of the studentinfo array. Reversing is done as following: 2. The 1st element is swapped with the last element (n 1). 3. The 2nd element is swapped with the element (n 2). 4. The 3rd element is swapped with the element (n 3). 5. And so on... public static void reversestudentinfoarray(tutorial[] StudentInfoToBeReversed) { Tutorial temp; int n = StudentInfoToBeReversed.length; for(int i = 0; i < n/2; i++) { temp = StudentInfoToBeReversed[i]; StudentInfoToBeReversed[i]= StudentInfoToBeReversed[(n 1) i]; StudentInfoToBeReversed[(n 1) i] = temp; Main method: does the following: 1. Create an array of objects studentinfo that contains students information. 2. Loop over the studentinfo array and create objects as elements of the array. I.e. adding elements to the array of objects "studentinfo": a. First, we ask the user to give us the ID of the current student. Then we check if the ID is unique or not. b. Then, we ask the user to give us the name the current student. c. After that, we set up the grades array of the current student. d. Now, we can create the object to store the current student information. e. Now that the studentinfo is created, we will fill the current student s grades. I.e. fill the elements of the "grades" array of the current student. 3. Now, we will reverse a certain student's grades after we give him a bonus of 2 to all his grades. Print the grades array of the selected student to assure that the bonus adding and the swapping worked properly. 4. Then, reverse the whole studentinfo array. Print the studentinfo array to assure that the swapping worked properly. 4

Exercise 1: Tutorial 12 Solutions A. public int find(int[] arr, int num, int n){ for (int i = 0; i < num; i++) { if (arr[i] == n) { return i; return 1; public boolean add (int[] arr, int num, int n) { if (num < arr.length) { if (find(arr, num, n) == 1){ arr[num] = n; num++; return true; else System.out.println("ERROR: ELEMENT ALREADY" else System.out.println("ERROR: ARRAY IS FULL"); return false; B. public void flipcoin (boolean[] flips, int num) { if (num < flips.length) { java.util.random r = new java.util.random(); boolean newflip = r.nextboolean(); flips[num] = newflip; num++; else System.out.println("ERROR: CAN NOT FLIP COIN"); C. public void deletetweet(string[] tweets,int numoftweets,string tweet){ boolean found = false; for (int i = 0; i < numoftweets &&!found; i++) { if (tweets[i].equalsignorecase(tweet)) { tweets[i] = tweets[numoftweets]; found = true; if (!found) System.out.println("ERROR: TWEET IS " + "ALREADY DELETED"); 5

D. public int findmove(double[] xmoves, double[] ymoves, double dx, double dy, int nummoves) { for (int i = 0; i < nummoves; i++) if ((xmoves[i] == dx) && (ymoves[i] == dy)) return i; return 1; Exercise 2: A. 1.if(cmr[0].equalsC(cmr[1])) System.out.println("They are Equal!"); // Or if(cmr[1].equalsc(cmr[0])) System.out.println("They are Equal!"); Note that we are sending a single element, which is sending a single object of type Customer to the method. 2. cmr[0].addsales(prices[1]); B. Exception in thread "main" java.lang.nullpointerexception at Tutorial13E1.main(Tutorial13E1.java:24) The answer is 3, we got a runtime error which is a Null Pointer Exception. This happened because we tried to retrieve a value of an instance variable (from within an instance method) for an object that hasn t been created! In other words, we created an array of objects, but we did NOT create each object of the array. That means we need to write the following statement before line 24 above: cmr[2] = new Customer(3, "Any Name", 0); C. Exception in thread "main" java.lang.arrayindexoutofboundsexception: 3 at Tutorial13E1.main(Tutorial13E1.java:29) The answer is C, we got a runtime error which is an Array Index Out Of Bound Exception. This happened because we tried to access the element cmr[3] which is not part of the array since the array has only 3 elements (indexed from 0 to 2). In other words, the error was caused from this operator (it should be < ): for (int i = 0; i <= cmr.length; i++) System.out.print("Name " + i + " = " + cmr[i].getname()); Exercise 3: public static void main(string[] args) { Scanner KB = new Scanner(System.in); // 1. System.out.print( How many students? ); int nstd = KB.nextInt(); Tutorial[] studentinfo = new Tutorial[nstd]; // 2. for (int i=0; i < studentinfo.length; i++) { 6

// 2.a. do { System.out.print( Enter id for student +(i+1)+ : ); int id = KB.nextInt(); while (foundid(studentinfo, id, i)); //2.b. System.out.print( Enter name for student +(i+1)+ : ); String name = KB.next(); // 2.c. System.out.print( How many grades for student +(i+1)+? ); int ngr = KB.nextInt(); double stdgrades = new double[ngr]; // 2.d. studentinfo[i] = new Tutorial(name,id, stdgrades); // 2.e. studentinfo[i].fillgrades(); // 3. System.out.println( Enter id for student to give bonus and reverse grades: ); int id = KB.nextInt(); int index = findindexbyid(studentinfo, id); if (id!= 1) { double[] gr = studentinfo[index].addbonus(2); studentinfo[index].reversegradesarray(gr); for (int i=0; i<gr.length; i++) System.out.println(gr[i]); else System.out.println( ID not found ); // 4. reversestudentinfoarray(studentinfo); for (int i=0; i<studentinfo.length; i++) System.out.println(studentInfo[i].getId()); 7