Problem Set Five. A. Pencil-and-Paper Exercises (44 points total) [1] 12 points (2 points for each part) use file Prob01.txt

Size: px
Start display at page:

Download "Problem Set Five. A. Pencil-and-Paper Exercises (44 points total) [1] 12 points (2 points for each part) use file Prob01.txt"

Transcription

1 Computer Science 1: Great Ideas in Computer Science Handout #12 Problem Set Five This assignment is designed to reinforce your comprehension of methods that manipulate Strings and other types of objects particularly arrays. Many of you will find Chapters 7 and 8 in the Reges textbook to be appropriate background reading before working on this problem set. Note that for 3 of the programming problems, you may pair up with one other CS-1 student. If you don t know anyone in the class but would like to work with someone, send to cs1@fas.harvard.edu and we will help find you a partner. Unless otherwise indicated, everything that the human would type to the computer has been underlined. Everything that the computer types is not. Electronic submission is due prior to 5 PM on Friday afternoon, April 8. Use the Unix command cs1submit ps5 (assuming you have created a folder in your cs1 directory named ps5 that contains your solutions). A. Pencil-and-Paper Exercises (44 points total) (your responses to each question in this part should appear in text files) [1] 12 points (2 points for each part) use file Prob01.txt Suppose a program contains the declaration String s = "Java, Java, Java ; Now evaluate each of the following independent expressions. If you can t remember how some of these String methods work, try looking at the documentation at download.oracle.com/javase/7/docs/api/ (a) (b) s.substring(0,4) == Java" s.lastindexof ( av") (c) s.indexof ( a, 5) (d) (e) s.indexof ( av", s.length()-10) s.substring(s.lastindexof (s.charat(5))) (f) s.substring (2, s.length()-3) Spring, 2016 Dr. H. H. Leitner

2 Computer Science 1: Great Ideas in Computer Science Page!2 [2] 4 points use file Prob02.txt The following simple program, which is supposed to create a 20-element array variable named cs1 that it fills with random integer values, contains a number of errors. Some of the blunders will cause an error message at compilation time, while others may cause an error at execution time. Find (and fix) all of them! class Foobar { public static void main (String [] args) { double [20] cs1; for (int i = 0; i <= cs1.length(); i++) cs1[i] = Math.random * 100; } } [3] 12 points (3 points for each part) use file Prob03.txt Write Java variable declarations to create new array objects of the following types. Note that you do NOT need to initialize any of them with specific values. (a) (b) (c) (d) a single-dimensioned array named a with the answers to 20 true/false quiz questions a single-dimensioned array named b that contains the average family size in the years 1900, 1920, 1940, 2010 a 2D array named c that contains the total number of inches of rainfall for a city in each of twelve months, recorded over a period of 5 years. a single-dimensioned array named d that contains the 4 candidates in some presidential primary election. You should define a Candidate class with private instance variables for the person s name and the number of votes received. Define a single Candidate constructor that accepts a candidate s name and number of votes. Do not bother defining any setters, getters or other instance methods.

3 ! Computer Science 1: Great Ideas in Computer Science Page!3 [4] 12 points (3 points for each part) use file Prob04.txt Suppose that final integer SIZE has been properly declared and initialized, and that an array named sample has been declared as follows: int [] sample = new int [SIZE]; Write one or more Java statements to perform the following. Note that each task is independent of the other three: (a) Initialize all array elements to the value 5. (b) (c) (d) Swap the first value in the array with the last value in the array Change any negative values to positive values (of the same magnitude) Print the contents of the odd-numbered locations in the arra [5] 4 points use file Prob05.txt Tic-tac-toe is a simple game in which each square in a 3 x 3 grid contains the letter X, the letter O or a blank space, as in the following: Write a single Java statement that constructs a two-dimensional array of char values (named tictactoe) and initializes it to the above configuration. Use nested initializers, as described in lecture.

4 Computer Science 1: Great Ideas in Computer Science Page!4 B. Programming Problems (125 points total) [6] 15 points use file Sentence.java Write a complete Java program that reads a line of input from the keyboard (using the nextline() Scanner method) and outputs either declarative, exclamatory, or interrogative according to whether the last character on the line was a period, an exclamation mark, or a question mark!!?!. Your program should output the message bad ending if the last character is none of these punctuation marks. [7] 20 points use file Vowels.java Define a method named vowelcount that accepts a String as its only parameter, and constructs (and returns) an array of integers that represents the counts of each vowel in the String. The array returned by your method should hold precisely 5 integers: the first is the count of A s, the second is the count of E s, the third is the count of I s, the fourth is O s, and the fifth is U s. For example, the call vowelcount ( I think, therefore I am ) should return an array containing the values [1, 3, 3, 1, 0]. Write a main program that thoroughly tests out vowelcount.

5 Computer Science 1: Great Ideas in Computer Science Page!5 [8] 25 points use file Duplication.java This problem may be worked on with one other CS1 student. If you decide to collaborate with another student, indicate the name of your helper as a comment inside the Duplication.java file. A common problem is to receive a list of values (e.g., addresses) that contain duplicates. Write a Java method named removeduplicates that accepts one argument, an array of String values, and returns a new array that has no duplicate values. The original array should not get reordered. For example, the code String [] values = {"A", "C", "C", "B", "A", "C", "B", "B", "A"}; String [] newlist = removeduplicates (values); for (int i = 0; i < newlist.length; i++) { System.out.print (values[i] + " "); } System.out.println(); should output A C B Write a main method that convincingly demonstrates your method in action. [9] 20 points modify files Rational.java and RatTest.java For the Rational class described in lecture, define a method named lessthanrat so that two rational numbers can be compared to determine if the first one is arithmetically less than the second one. For example, the expression a.lessthanrat(b) is true, given Rational a = new Rational (8, 16); Rational b = new Rational (2, 3); Be sure to copy the Rational.java file from the ~cs1/java directory to your own account in order to test out your solution. You can also copy the RatTest.java file, and modify it in order to test your lessthanrat method.

6 Computer Science 1: Great Ideas in Computer Science Page!6 [10] 20 points use files Pizza.java and PizzaParty.java This problem also may be worked on with one other CS1 student. If you decide to do so, indicate the name of your helper as a comment inside the PizzaParty file. Pizzas can be ordered in several sizes. Some pizza parlors cut all pizzas into 8 slices, while others get more slices out of the larger pizza pies. It might be useful to know what size pie offers the best deal in terms of cost per slice or cost per square inch of pizza. Here s a Java program to help determine these facts: public class PizzaParty { public static void main(string[] args) { Pizza appetizer = new Pizza ("Pepperoni", 16, 10.50, 10); Pizza maincourse = new Pizza ("Anchovy & Pineapple, 20, 11.95, 8); printpizzastats (appetizer); System.out.println(); printpizzastats (maincourse); } } public static void printpizzastats (Pizza p) { System.out.printf ("Your %s pizza has %.2f square inches " + " per slice.\n", p.getname(), p.areaperslice()); System.out.printf ("One slice costs $%.2f, which comes + " to $%.3f per square inch.\n", p.costperslice(), p.costpersquareinch() ); }

7 Computer Science 1: Great Ideas in Computer Science Page!7 Your task is to implement the Pizza class with instance variables and methods Note that the Pizza constructor accepts 4 parameters: the first is the name of the pizza, the second argument is the radius of the pizza, the third argument is the total price of the pizza, and the fourth argument is the number of slices this pizza will be cut into. Please include the PizzaParty class with your submission. If the Pizza class gets properly defined, here is what your program should look like in action (note the use of printf to format the output of double values in an appropriate way). Your Pepperoni pizza has square inches per slice. One slice costs $1.05, which comes to $0.052 per square inch. Your Anchovy & Pepper pizza has square inches per slice. One slice costs $1.49, which comes to $0.038 per square inch. [11] 25 points use file PigLatin.java Write a method named piggie that accepts a String argument containing a single English language word, and returns the Pig Latin equivalent. Pig Latin is English, but with the initial consonant sound moved to the end of the word, followed by ay. However, words that begin with vowels simply have way appended to the end of the word. For example, the input deepest gets translated into eepest-day shade gets translated to ade-shay Obama gets translated to Obama-way, and you gets translated to ou-yay queen gets translated to een-quay (note the u stays with q ) by gets translated to y-bay (note that y is a vowel) Write a main method that tests your program out by asking the user to input a complete line of text (basically an English sentence) and then outputs the equivalent in Pig Latin by calling on your piggie method repeatedly (once for each word in the sentence). Consider using the next() and hasnext() methods of the Scanner class to simplify the programming.

8 Computer Science 1: Great Ideas in Computer Science Page!8 C. Additional Problems (up to 45 points) You must turn in a solution to any one of the following problems. For extra credit, you may turn in a solution to at most any two additional problems (in other words, one or two problems IN ADDITION to the required problem). Indicate which problems are for extra credit. [12] 15 points use file RepeatedDigits.java Write a Java program that allows the user to input an integer value; after this number is entered, your program will print out how many times each of the digits from 0 through 9 appeared in your input value. Here is how your program might appear in action: Please enter an integer: Digit: Occurrences: Note that leading zeros should be ignored; negative numbers can be considered valid input by somehow ignoring the - sign. The occurrences should be stored in a single array. [13] 15 points use file ArrayIntersect.java Write a Java method named intersection that accepts two arguments, both arrays of integers; these arrays may contain a different number of elements from each other. Your method must return the value true if there exists an integer value, k, that is contained in both tables. If no such integer exists, then your method should return the value false. You are not to assume that k is any integer value in particular! Write a main() method that convincingly demonstrates the features of your method.

9 Computer Science 1: Great Ideas in Computer Science Page!9 [14] 15 points use file MagicSquare.java A magic square is an n x n grid of the integers 1 through n 2 that sum to the same value across rows, down columns, and along the two diagonals. An example is! Note how every row, column and diagonal in this 3 x 3 grid sums to the value 15. An old method for constructing magic squares of an odd order was devised by the mathematician de la Loubére. It involves placing the next number of the magic square DIAGONALLY UP AND TO THE RIGHT OF THE PREVIOUS NUMBER, with the following caveats: One row up from the top row lands you in the bottom row. One column right from the rightmost column lands you in the leftmost column. If the desired cell is already occupied, then instead place the next number below the previous one. Begin the whole process by placing the number 1 in the middle of the top row. Write a complete Java program to read an odd integer input from the keyboard, and then display a magic square of that order using the ideas presented above.

10 Computer Science 1: Great Ideas in Computer Science Page!10 [15] 15 points use file Roman.java Write a program to read in a string of characters that represent a Roman numeral and then convert it to Arabic form (an integer). The character values for Roman numerals are as follows: Roman Symbol Value M 1000 D 500 C 100 L 50 X 10 V 5 I 1 Test your program with the following data: LXXXVII (87), CCXIX (219), MCCCLIV (1354), MMDCLXXIII (2673) and MCDLXXVI (1476). If you don t know (or can t remember) how Roman numerals work, Google it! [16] 15 points use file MindtheGap.java Write a static method named mingap that takes an integer array as a parameter and that returns the minimum gap between adjacent values in the array. The gap between two adjacent values in a list is defined as the second value minus the first value. For example, suppose a variable called "list" is an array of integers that stores the following sequence of values: {1, 3, 6, 7, 12} The first gap is 2 (3-1), the second gap is 3 (6-3), the third gap is 1 (7-6) and the fourth gap is 5 (12-7). Thus, the call mingap (list) should return 1 because that is the smallest gap in the list. Notice that the minimum gap could

11 Computer Science 1: Great Ideas in Computer Science Page!11 be a negative number. For example, if list stores the following sequence of values {3, 5, 11, 4, 8} then the gaps would be computed as 2 (5-3), 6 (11-5), -7 (4-11), and 4 (8-4). Of these values, -7 is the smallest, so it would be returned. By the way, this gap information can be helpful for determining other properties of the list. For example, if the minimum gap is greater than or equal to 0, then you know the list is in sorted (nondecreasing) order. (Do you understand why?) If the gap is greater than 0, then you know the list is both sorted and contains unique values (i.e., it is strictly increasing). If your method is passed an array with fewer than 2 elements, mingap should return 0. But sure to convincingly test your method out on a variety of arrays using a main program of your own design. [17] 15 points use files TicTacToe.java and TicTacToeBoard.java Write a program that allows two people to play a game of tic-tac-toe, with the computer acting as a referee. Here is what your program might look like in action: Welcome! Tic-Tac-Toe is a two player game. Enter player one's name: Foo Enter player two's name: Bar Players take turns marking a square. Only squares not already marked can be picked. Once a player has marked three squares in a row, he or she wins! If all squares are marked and no three squares are the same, a tied game is declared. Have Fun! Game board: It is Foo's turn. Pick a row between 1 and 3: 1 Pick a column between 1 and 3: 1 Game board:

12 Computer Science 1: Great Ideas in Computer Science Page!12 X It is Bar's turn. Pick a row between 1 and 3: 2 Pick a column between 1 and 3: 2 Game board: X O It is Foo's turn. Pick a row between 1 and 3: 2 Pick a column between 1 and 3: 2 ILLEGAL CHOICE! TRY AGAIN... Pick a row between 1 and 3: 2 Pick a column between 1 and 3: 1 Game board: X X O It is Bar's turn. Pick a row between 1 and 3: 3 Pick a column between 1 and 3: 1 Game board: X X O O It is Foo's turn. Pick a row between 1 and 3: 3 Pick a column between 1 and 3: 3 Game board: X X O O X It is Bar's turn. Pick a row between 1 and 3: 1 Pick a column between 1 and 3: 3

13 Computer Science 1: Great Ideas in Computer Science Page!13 Game board: X O X O O X Game Over - Bar WINS!!! In solving this problem, create a TicTacToeBoard class that contains a two- dimensional array representing the current state of a tic-tac-toe board. Initially, every element of this array could contain a space character, to indicate it is empty. Your TicTacToeBoard class should only have private variables and these and only these public methods: // constructor public TicTacToeBoard() { } // returns a string representation of the board public String tostring() { } // tries to play c (X or O) at row, col // returns true if square was legal and not occupied public boolean makemove (int row, int col, char c) { } // returns true if the board is a win for either X or O public boolean iswin() { } Your tostring method in this class will make it possible for the TicTacToe client program to print the board as shown in the above output. Your main program will alternately let each of the two players make a move, but not allow any move that is illegal either because a particular square is already occupied, or because a value less than 1 or greater than 3 has been input for the row or column position. After each turn is made the computer should check if any row, column or diagonal contains three X marks or three O marks; if so, a winner should be declared and the game should end at that point. If nobody has won after 9 moves, a tie should be declared.

14 Computer Science 1: Great Ideas in Computer Science Page!14 [18] 15 points use file CardinalOrdinal.java And this problem may also be worked on with one other CS1 student. If you decide to do so, indicate the name of your helper as a comment inside the CardinalOrdinal.java file. Like most other languages, English includes two types of numbers: cardinal numbers (such as one, two, three, and four) that are used in counting, and ordinal numbers (such as first, second, third, and fourth) that are used to indicate a position in a sequence. In numeric form, ordinals are usually indicated by writing the digits in the number, followed by the last two letters of the English word that names the corresponding ordinal. Thus, the ordinal numbers first, second, third, and fourth often appear in print as 1st, 2nd, 3rd, and 4th. follows: The general rule for determining the SUFFIX of an ordinal can be defined as Numbers ending in the digit 1, 2, and 3, take the suffixes st, nd, and rd, respectively, unless the number ends with the two-digit combination 11, 12, or 13. Those numbers, and any numbers not ending with a 1, 2, or 3, take the suffix th. Your task in this problem is to write a message named createordinalform (n) that takes an integer n and returns a String indicating the corresponding ordinal number. For example, your method should return the following values: createordinalform (1) returns the String 1st createordinalform (2) returns the String 2nd createordinalform (3) returns the String 3rd createordinalform (10) returns the String 10th createordinalform (11) returns the String 11th createordinalform (12) returns the String 12th createordinalform (21) returns the String 21st createordinalform (42) returns the String 42nd createordinalform (101) returns the String 101st createordinalform (111) returns the String 111th You will need to write a main method that tests your createordinalform method by using the above examples.

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

J a v a Quiz (Unit 3, Test 0 Practice) Computer Science S-111a: Intensive Introduction to Computer Science Using Java Handout #11 Your Name Teaching Fellow J a v a Quiz (Unit 3, Test 0 Practice) Multiple-choice questions are worth 2 points

More information

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

AP Computer Science Java Mr. Clausen Program 9A, 9B AP Computer Science Java Mr. Clausen Program 9A, 9B PROGRAM 9A I m_sort_of_searching (20 points now, 60 points when all parts are finished) The purpose of this project is to set up a program that will

More information

Sample CSE8A midterm Multiple Choice (circle one)

Sample CSE8A midterm Multiple Choice (circle one) Sample midterm Multiple Choice (circle one) (2 pts) Evaluate the following Boolean expressions and indicate whether short-circuiting happened during evaluation: Assume variables with the following names

More information

In this Chapter you ll learn:

In this Chapter you ll learn: 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

More information

Project 2: Bejeweled

Project 2: Bejeweled Project 2: Bejeweled Project Objective: Post: Tuesday March 26, 2013. Due: 11:59PM, Monday April 15, 2013 1. master the process of completing a programming project in UNIX. 2. get familiar with command

More information

Programming Languages CIS 443

Programming Languages CIS 443 Course Objectives Programming Languages CIS 443 0.1 Lexical analysis Syntax Semantics Functional programming Variable lifetime and scoping Parameter passing Object-oriented programming Continuations Exception

More information

Introduction to Java. CS 3: Computer Programming in Java

Introduction to Java. CS 3: Computer Programming in Java Introduction to Java CS 3: Computer Programming in Java Objectives Begin with primitive data types Create a main class with helper methods Learn how to call built-in class methods and instance methods

More information

Ready, Set, Go! Math Games for Serious Minds

Ready, Set, Go! Math Games for Serious Minds Math Games with Cards and Dice presented at NAGC November, 2013 Ready, Set, Go! Math Games for Serious Minds Rande McCreight Lincoln Public Schools Lincoln, Nebraska Math Games with Cards Close to 20 -

More information

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

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013 Masters programmes in Computer Science and Information Systems Object-Oriented Design and Programming Sample module entry test xxth December 2013 This sample paper has more questions than the real paper

More information

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:

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: Lecture 7 Picking Balls From an Urn The problem: An urn has n (n = 10) balls numbered from 0 to 9 A ball is selected at random, its' is number noted, it is set aside, and another ball is selected from

More information

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

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals 1 Recall From Last Time: Java Program import java.util.scanner; public class EggBasket { public static void main(string[]

More information

Iteration CHAPTER 6. Topic Summary

Iteration CHAPTER 6. Topic Summary CHAPTER 6 Iteration TOPIC OUTLINE 6.1 while Loops 6.2 for Loops 6.3 Nested Loops 6.4 Off-by-1 Errors 6.5 Random Numbers and Simulations 6.6 Loop Invariants (AB only) Topic Summary 6.1 while Loops Many

More information

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

The resulting tile cannot merge with another tile again in the same move. When a 2048 tile is created, the player wins. 2048 2048 is number puzzle game created in March 2014 by 19-year-old Italian web developer Gabriele Cirulli, in which the objective is to slide numbered tiles on a grid to combine them and create a tile

More information

CmpSci 187: Programming with Data Structures Spring 2015

CmpSci 187: Programming with Data Structures Spring 2015 CmpSci 187: Programming with Data Structures Spring 2015 Lecture #12 John Ridgway March 10, 2015 1 Implementations of Queues 1.1 Linked Queues A Linked Queue Implementing a queue with a linked list is

More information

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

1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius Programming Concepts Practice Test 1 1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius 2) Consider the following statement: System.out.println("1

More information

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

Two-Dimensional Arrays. Multi-dimensional Arrays. Two-Dimensional Array Indexing Multi-dimensional Arrays The elements of an array can be any type Including an array type So int 2D[] []; declares an array of arrays of int Two dimensional arrays are useful for representing tables of

More information

Chapter 2: Elements of Java

Chapter 2: Elements of Java Chapter 2: Elements of Java Basic components of a Java program Primitive data types Arithmetic expressions Type casting. The String type (introduction) Basic I/O statements Importing packages. 1 Introduction

More information

1. Define: (a) Variable, (b) Constant, (c) Type, (d) Enumerated Type, (e) Identifier.

1. Define: (a) Variable, (b) Constant, (c) Type, (d) Enumerated Type, (e) Identifier. Study Group 1 Variables and Types 1. Define: (a) Variable, (b) Constant, (c) Type, (d) Enumerated Type, (e) Identifier. 2. What does the byte 00100110 represent? 3. What is the purpose of the declarations

More information

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

System.out.println(\nEnter Product Number 1-5 (0 to stop and view summary) : Benjamin Michael Java Homework 3 10/31/2012 1) Sales.java Code // Sales.java // Program calculates sales, based on an input of product // number and quantity sold import java.util.scanner; public class

More information

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

Mobile App Design Project #1 Java Boot Camp: Design Model for Chutes and Ladders Board Game Mobile App Design Project #1 Java Boot Camp: Design Model for Chutes and Ladders Board Game Directions: In mobile Applications the Control Model View model works to divide the work within an application.

More information

CS170 Lab 11 Abstract Data Types & Objects

CS170 Lab 11 Abstract Data Types & Objects CS170 Lab 11 Abstract Data Types & Objects Introduction: Abstract Data Type (ADT) An abstract data type is commonly known as a class of objects An abstract data type in a program is used to represent (the

More information

Arrays in Java. Working with Arrays

Arrays in Java. Working with Arrays Arrays in Java So far we have talked about variables as a storage location for a single value of a particular data type. We can also define a variable in such a way that it can store multiple values. Such

More information

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

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007 Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007 The Java Type System By now, you have seen a fair amount of Java. Time to study in more depth the foundations of the language,

More information

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

Introduction to Java Applications. 2005 Pearson Education, Inc. All rights reserved. 1 2 Introduction to Java Applications 2.2 First Program in Java: Printing a Line of Text 2 Application Executes when you use the java command to launch the Java Virtual Machine (JVM) Sample program Displays

More information

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

1.4 Arrays Introduction to Programming in Java: An Interdisciplinary Approach Robert Sedgewick and Kevin Wayne Copyright 2002 2010 2/6/11 12:33 PM! 1.4 Arrays Introduction to Programming in Java: An Interdisciplinary Approach Robert Sedgewick and Kevin Wayne Copyright 2002 2010 2/6/11 12:33 PM! A Foundation for Programming any program you might want

More information

1.00 Lecture 1. Course information Course staff (TA, instructor names on syllabus/faq): 2 instructors, 4 TAs, 2 Lab TAs, graders

1.00 Lecture 1. Course information Course staff (TA, instructor names on syllabus/faq): 2 instructors, 4 TAs, 2 Lab TAs, graders 1.00 Lecture 1 Course Overview Introduction to Java Reading for next time: Big Java: 1.1-1.7 Course information Course staff (TA, instructor names on syllabus/faq): 2 instructors, 4 TAs, 2 Lab TAs, graders

More information

Chapter 3. Input and output. 3.1 The System class

Chapter 3. Input and output. 3.1 The System class Chapter 3 Input and output The programs we ve looked at so far just display messages, which doesn t involve a lot of real computation. This chapter will show you how to read input from the keyboard, use

More information

Lab Experience 17. Programming Language Translation

Lab Experience 17. Programming Language Translation Lab Experience 17 Programming Language Translation Objectives Gain insight into the translation process for converting one virtual machine to another See the process by which an assembler translates assembly

More information

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

First Java Programs. V. Paúl Pauca. CSC 111D Fall, 2015. Department of Computer Science Wake Forest University. Introduction to Computer Science First Java Programs V. Paúl Pauca Department of Computer Science Wake Forest University CSC 111D Fall, 2015 Hello World revisited / 8/23/15 The f i r s t o b l i g a t o r y Java program @author Paul Pauca

More information

Introduction to Java

Introduction to Java Introduction to Java The HelloWorld program Primitive data types Assignment and arithmetic operations User input Conditional statements Looping Arrays CSA0011 Matthew Xuereb 2008 1 Java Overview A high

More information

Moving from CS 61A Scheme to CS 61B Java

Moving from CS 61A Scheme to CS 61B Java Moving from CS 61A Scheme to CS 61B Java Introduction Java is an object-oriented language. This document describes some of the differences between object-oriented programming in Scheme (which we hope you

More information

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

Chapter 2. println Versus print. Formatting Output withprintf. System.out.println for console output. console output. Console Input and Output Chapter 2 Console Input and Output System.out.println for console output System.out is an object that is part of the Java language println is a method invoked dby the System.out object that can be used

More information

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

Part I. Multiple Choice Questions (2 points each): Part I. Multiple Choice Questions (2 points each): 1. Which of the following is NOT a key component of object oriented programming? (a) Inheritance (b) Encapsulation (c) Polymorphism (d) Parallelism ******

More information

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

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner. Handout 1 CS603 Object-Oriented Programming Fall 15 Page 1 of 11 Handout 1 Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner. Java

More information

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

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013 Oct 4, 2013, p 1 Name: CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013 1. (max 18) 4. (max 16) 2. (max 12) 5. (max 12) 3. (max 24) 6. (max 18) Total: (max 100)

More information

AP Computer Science Java Subset

AP Computer Science Java Subset APPENDIX A AP Computer Science Java Subset The AP Java subset is intended to outline the features of Java that may appear on the AP Computer Science A Exam. The AP Java subset is NOT intended as an overall

More information

ALGEBRA. sequence, term, nth term, consecutive, rule, relationship, generate, predict, continue increase, decrease finite, infinite

ALGEBRA. sequence, term, nth term, consecutive, rule, relationship, generate, predict, continue increase, decrease finite, infinite ALGEBRA Pupils should be taught to: Generate and describe sequences As outcomes, Year 7 pupils should, for example: Use, read and write, spelling correctly: sequence, term, nth term, consecutive, rule,

More information

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

Arrays. number: Motivation. Prof. Stewart Weiss. Software Design Lecture Notes Arrays Motivation Suppose that we want a program that can read in a list of numbers and sort that list, or nd the largest value in that list. To be concrete about it, suppose we have 15 numbers to read in from

More information

Java Basics: Data Types, Variables, and Loops

Java Basics: Data Types, Variables, and Loops Java Basics: Data Types, Variables, and Loops If debugging is the process of removing software bugs, then programming must be the process of putting them in. - Edsger Dijkstra Plan for the Day Variables

More information

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

The following program is aiming to extract from a simple text file an analysis of the content such as: Text Analyser Aim The following program is aiming to extract from a simple text file an analysis of the content such as: Number of printable characters Number of white spaces Number of vowels Number of

More information

Introduction to Programming

Introduction to Programming Introduction to Programming Lecturer: Steve Maybank Department of Computer Science and Information Systems sjmaybank@dcs.bbk.ac.uk Spring 2015 Week 2b: Review of Week 1, Variables 16 January 2015 Birkbeck

More information

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

Chulalongkorn University International School of Engineering Department of Computer Engineering 2140105 Computer Programming Lab. Chulalongkorn University Name International School of Engineering Student ID Department of Computer Engineering Station No. 2140105 Computer Programming Lab. Date Lab 2 Using Java API documents, command

More information

Object-Oriented Programming in Java

Object-Oriented Programming in Java CSCI/CMPE 3326 Object-Oriented Programming in Java Class, object, member field and method, final constant, format specifier, file I/O Dongchul Kim Department of Computer Science University of Texas Rio

More information

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C Basic Java Constructs and Data Types Nuts and Bolts Looking into Specific Differences and Enhancements in Java compared to C 1 Contents Hello World Program Statements Explained Java Program Structure in

More information

12-6 Write a recursive definition of a valid Java identifier (see chapter 2).

12-6 Write a recursive definition of a valid Java identifier (see chapter 2). CHAPTER 12 Recursion Recursion is a powerful programming technique that is often difficult for students to understand. The challenge is explaining recursion in a way that is already natural to the student.

More information

Term Project: Roulette

Term Project: Roulette Term Project: Roulette DCY Student January 13, 2006 1. Introduction The roulette is a popular gambling game found in all major casinos. In contrast to many other gambling games such as black jack, poker,

More information

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program. Name: Class: Date: Exam #1 - Prep True/False Indicate whether the statement is true or false. 1. Programming is the process of writing a computer program in a language that the computer can respond to

More information

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

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4 JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4 NOTE: SUN ONE Studio is almost identical with NetBeans. NetBeans is open source and can be downloaded from www.netbeans.org. I

More information

Working with whole numbers

Working with whole numbers 1 CHAPTER 1 Working with whole numbers In this chapter you will revise earlier work on: addition and subtraction without a calculator multiplication and division without a calculator using positive and

More information

Unit 6. Loop statements

Unit 6. Loop statements Unit 6 Loop statements Summary Repetition of statements The while statement Input loop Loop schemes The for statement The do statement Nested loops Flow control statements 6.1 Statements in Java Till now

More information

Text Processing In Java: Characters and Strings

Text Processing In Java: Characters and Strings Text Processing In Java: Characters and Strings Wellesley College CS230 Lecture 03 Monday, February 5 Handout #10 (Revised Friday, February 9) Reading: Downey: Chapter 7 Problem Set: Assignment #1 due

More information

CS 106 Introduction to Computer Science I

CS 106 Introduction to Computer Science I CS 106 Introduction to Computer Science I 01 / 21 / 2014 Instructor: Michael Eckmann Today s Topics Introduction Homework assignment Review the syllabus Review the policies on academic dishonesty and improper

More information

n 2 + 4n + 3. The answer in decimal form (for the Blitz): 0, 75. Solution. (n + 1)(n + 3) = n + 3 2 lim m 2 1

n 2 + 4n + 3. The answer in decimal form (for the Blitz): 0, 75. Solution. (n + 1)(n + 3) = n + 3 2 lim m 2 1 . Calculate the sum of the series Answer: 3 4. n 2 + 4n + 3. The answer in decimal form (for the Blitz):, 75. Solution. n 2 + 4n + 3 = (n + )(n + 3) = (n + 3) (n + ) = 2 (n + )(n + 3) ( 2 n + ) = m ( n

More information

Pigeonhole Principle Solutions

Pigeonhole Principle Solutions Pigeonhole Principle Solutions 1. Show that if we take n + 1 numbers from the set {1, 2,..., 2n}, then some pair of numbers will have no factors in common. Solution: Note that consecutive numbers (such

More information

Arrays. Atul Prakash Readings: Chapter 10, Downey Sun s Java tutorial on Arrays: http://java.sun.com/docs/books/tutorial/java/nutsandbolts/arrays.

Arrays. Atul Prakash Readings: Chapter 10, Downey Sun s Java tutorial on Arrays: http://java.sun.com/docs/books/tutorial/java/nutsandbolts/arrays. Arrays Atul Prakash Readings: Chapter 10, Downey Sun s Java tutorial on Arrays: http://java.sun.com/docs/books/tutorial/java/nutsandbolts/arrays.html 1 Grid in Assignment 2 How do you represent the state

More information

Sources: On the Web: Slides will be available on:

Sources: On the Web: Slides will be available on: C programming Introduction The basics of algorithms Structure of a C code, compilation step Constant, variable type, variable scope Expression and operators: assignment, arithmetic operators, comparison,

More information

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

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O 1 Sending Output to a (Text) File import java.util.scanner; import java.io.*; public class TextFileOutputDemo1 public static void

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 4: Conditional Execution These lecture notes are copyright (C) Marty Stepp and Stuart Reges, 2007. They may not be rehosted, sold, or modified without expressed permission

More information

APP INVENTOR. Test Review

APP INVENTOR. Test Review APP INVENTOR Test Review Main Concepts App Inventor Lists Creating Random Numbers Variables Searching and Sorting Data Linear Search Binary Search Selection Sort Quick Sort Abstraction Modulus Division

More information

Java CPD (I) Frans Coenen Department of Computer Science

Java CPD (I) Frans Coenen Department of Computer Science Java CPD (I) Frans Coenen Department of Computer Science Content Session 1, 12:45-14:30 (First Java Programme, Inheritance, Arithmetic) Session 2, 14:45-16:45 (Input and Programme Constructs) Materials

More information

Current California Math Standards Balanced Equations

Current California Math Standards Balanced Equations Balanced Equations Current California Math Standards Balanced Equations Grade Three Number Sense 1.0 Students understand the place value of whole numbers: 1.1 Count, read, and write whole numbers to 10,000.

More information

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

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language Translation Translating to Java Introduction to Computer Programming The job of a programmer is to translate a problem description into a computer language. You need to be able to convert a problem description

More information

Chapter 3. Cartesian Products and Relations. 3.1 Cartesian Products

Chapter 3. Cartesian Products and Relations. 3.1 Cartesian Products Chapter 3 Cartesian Products and Relations The material in this chapter is the first real encounter with abstraction. Relations are very general thing they are a special type of subset. After introducing

More information

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

Problem 1. CS 61b Summer 2005 Homework #2 Due July 5th at the beginning of class CS 61b Summer 2005 Homework #2 Due July 5th at the beginning of class This homework is to be done individually. You may, of course, ask your fellow classmates for help if you have trouble editing files,

More information

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

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming 1 2 Foreword First of all, this book isn t really for dummies. I wrote it for myself and other kids who are on the team. Everything

More information

objectives chapter Define classes that act like blueprints for new objects, made of variables and methods. Explain encapsulation and Java modifiers.

objectives chapter Define classes that act like blueprints for new objects, made of variables and methods. Explain encapsulation and Java modifiers. 4 chapter objectives Define classes that act like blueprints for new objects, made of variables and methods. Explain encapsulation and Java modifiers. Explore the details of method declarations. Review

More information

arrays C Programming Language - Arrays

arrays C Programming Language - Arrays arrays So far, we have been using only scalar variables scalar meaning a variable with a single value But many things require a set of related values coordinates or vectors require 3 (or 2, or 4, or more)

More information

Simplifying Improper Fractions Poster

Simplifying Improper Fractions Poster Simplifying Improper Fractions Poster Congratulations on your purchase of this Really Good Stuff Simplifying Improper Fractions Poster a reference tool showing students how to change improper fractions

More information

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

1. Use the class definition above to circle and identify the parts of code from the list given in parts a j. public class Foo { private Bar _bar; public Foo() { _bar = new Bar(); public void foobar() { _bar.moveforward(25); 1. Use the class definition above to circle and identify the parts of code from the list

More information

1 Description of The Simpletron

1 Description of The Simpletron Simulating The Simpletron Computer 50 points 1 Description of The Simpletron In this assignment you will write a program to simulate a fictional computer that we will call the Simpletron. As its name implies

More information

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

COSC 111: Computer Programming I. Dr. Bowen Hui University of Bri>sh Columbia Okanagan COSC 111: Computer Programming I Dr. Bowen Hui University of Bri>sh Columbia Okanagan 1 Today Review slides from week 2 Review another example with classes and objects Review classes in A1 2 Discussion

More information

Kenken For Teachers. Tom Davis tomrdavis@earthlink.net http://www.geometer.org/mathcircles June 27, 2010. Abstract

Kenken For Teachers. Tom Davis tomrdavis@earthlink.net http://www.geometer.org/mathcircles June 27, 2010. Abstract Kenken For Teachers Tom Davis tomrdavis@earthlink.net http://www.geometer.org/mathcircles June 7, 00 Abstract Kenken is a puzzle whose solution requires a combination of logic and simple arithmetic skills.

More information

A binary search tree or BST is a binary tree that is either empty or in which the data element of each node has a key, and:

A binary search tree or BST is a binary tree that is either empty or in which the data element of each node has a key, and: Binary Search Trees 1 The general binary tree shown in the previous chapter is not terribly useful in practice. The chief use of binary trees is for providing rapid access to data (indexing, if you will)

More information

Sudoku puzzles and how to solve them

Sudoku puzzles and how to solve them Sudoku puzzles and how to solve them Andries E. Brouwer 2006-05-31 1 Sudoku Figure 1: Two puzzles the second one is difficult A Sudoku puzzle (of classical type ) consists of a 9-by-9 matrix partitioned

More information

Comp 248 Introduction to Programming

Comp 248 Introduction to Programming Comp 248 Introduction to Programming Chapter 2 - Console Input & Output Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal, Canada These slides has been

More information

To Evaluate an Algebraic Expression

To Evaluate an Algebraic Expression 1.5 Evaluating Algebraic Expressions 1.5 OBJECTIVES 1. Evaluate algebraic expressions given any signed number value for the variables 2. Use a calculator to evaluate algebraic expressions 3. Find the sum

More information

Introduction to Data Structures

Introduction to Data Structures Introduction to Data Structures Albert Gural October 28, 2011 1 Introduction When trying to convert from an algorithm to the actual code, one important aspect to consider is how to store and manipulate

More information

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

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. Exam Name MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. 1) The JDK command to compile a class in the file Test.java is A) java Test.java B) java

More information

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

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner java.util.scanner java.util.scanner is a class in the Java API used to create a Scanner object, an extremely versatile object that you can use to input alphanumeric characters from several input sources

More information

A TOOL FOR DATA STRUCTURE VISUALIZATION AND USER-DEFINED ALGORITHM ANIMATION

A TOOL FOR DATA STRUCTURE VISUALIZATION AND USER-DEFINED ALGORITHM ANIMATION A TOOL FOR DATA STRUCTURE VISUALIZATION AND USER-DEFINED ALGORITHM ANIMATION Tao Chen 1, Tarek Sobh 2 Abstract -- In this paper, a software application that features the visualization of commonly used

More information

Guidance paper - The use of calculators in the teaching and learning of mathematics

Guidance paper - The use of calculators in the teaching and learning of mathematics Guidance paper - The use of calculators in the teaching and learning of mathematics Background and context In mathematics, the calculator can be an effective teaching and learning resource in the primary

More information

Some Scanner Class Methods

Some Scanner Class Methods Keyboard Input Scanner, Documentation, Style Java 5.0 has reasonable facilities for handling keyboard input. These facilities are provided by the Scanner class in the java.util package. A package is a

More information

Example of a Java program

Example of a Java program Example of a Java program class SomeNumbers static int square (int x) return x*x; public static void main (String[] args) int n=20; if (args.length > 0) // change default n = Integer.parseInt(args[0]);

More information

The Snake Game Java Case Study

The Snake Game Java Case Study The Snake Game Java Case Study John Latham January 27, 2014 Contents 1 Introduction 2 2 Learning outcomes 2 3 Description of the game 2 4 The classes of the program 4 5 The laboratory exercise and optional

More information

Parentheses in Number Sentences

Parentheses in Number Sentences Parentheses in Number Sentences Objective To review the use of parentheses. www.everydaymathonline.com epresentations etoolkit Algorithms Practice EM Facts Workshop Game Family Letters Assessment Management

More information

MIDTERM 1 REVIEW WRITING CODE POSSIBLE SOLUTION

MIDTERM 1 REVIEW WRITING CODE POSSIBLE SOLUTION MIDTERM 1 REVIEW WRITING CODE POSSIBLE SOLUTION 1. Write a loop that computes (No need to write a complete program) 100 1 99 2 98 3 97... 4 3 98 2 99 1 100 Note: this is not the only solution; double sum

More information

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following: In creating objects of the type, we have used statements similar to the following: f = new (); The parentheses in the expression () makes it look like a method, yet we never created such a method in our

More information

Lecture 22: C Programming 4 Embedded Systems

Lecture 22: C Programming 4 Embedded Systems Lecture 22: C Programming 4 Embedded Systems Today s Goals Basic C programming process Variables and constants in C Pointers to access addresses Using a High Level Language High-level languages More human

More information

Excel: Introduction to Formulas

Excel: Introduction to Formulas Excel: Introduction to Formulas Table of Contents Formulas Arithmetic & Comparison Operators... 2 Text Concatenation... 2 Operator Precedence... 2 UPPER, LOWER, PROPER and TRIM... 3 & (Ampersand)... 4

More information

CS 1133, LAB 2: FUNCTIONS AND TESTING http://www.cs.cornell.edu/courses/cs1133/2015fa/labs/lab02.pdf

CS 1133, LAB 2: FUNCTIONS AND TESTING http://www.cs.cornell.edu/courses/cs1133/2015fa/labs/lab02.pdf CS 1133, LAB 2: FUNCTIONS AND TESTING http://www.cs.cornell.edu/courses/cs1133/2015fa/labs/lab02.pdf First Name: Last Name: NetID: The purpose of this lab is to help you to better understand functions:

More information

Section 6 Spring 2013

Section 6 Spring 2013 Print Your Name You may use one page of hand written notes (both sides) and a dictionary. No i-phones, calculators or any other type of non-organic computer. Do not take this exam if you are sick. Once

More information

Inside the Java Virtual Machine

Inside the Java Virtual Machine CS1Bh Practical 2 Inside the Java Virtual Machine This is an individual practical exercise which requires you to submit some files electronically. A system which measures software similarity will be used

More information

This loop prints out the numbers from 1 through 10 on separate lines. How does it work? Output: 1 2 3 4 5 6 7 8 9 10

This loop prints out the numbers from 1 through 10 on separate lines. How does it work? Output: 1 2 3 4 5 6 7 8 9 10 Java Loops & Methods The while loop Syntax: while ( condition is true ) { do these statements Just as it says, the statements execute while the condition is true. Once the condition becomes false, execution

More information

Row Echelon Form and Reduced Row Echelon Form

Row Echelon Form and Reduced Row Echelon Form These notes closely follow the presentation of the material given in David C Lay s textbook Linear Algebra and its Applications (3rd edition) These notes are intended primarily for in-class presentation

More information

COMPUTER SCIENCE. Paper 1 (THEORY)

COMPUTER SCIENCE. Paper 1 (THEORY) COMPUTER SCIENCE Paper 1 (THEORY) (Three hours) Maximum Marks: 70 (Candidates are allowed additional 15 minutes for only reading the paper. They must NOT start writing during this time) -----------------------------------------------------------------------------------------------------------------------

More information

Acing Math (One Deck At A Time!): A Collection of Math Games. Table of Contents

Acing Math (One Deck At A Time!): A Collection of Math Games. Table of Contents Table of Contents Introduction to Acing Math page 5 Card Sort (Grades K - 3) page 8 Greater or Less Than (Grades K - 3) page 9 Number Battle (Grades K - 3) page 10 Place Value Number Battle (Grades 1-6)

More information

Session 7 Fractions and Decimals

Session 7 Fractions and Decimals Key Terms in This Session Session 7 Fractions and Decimals Previously Introduced prime number rational numbers New in This Session period repeating decimal terminating decimal Introduction In this session,

More information

public static void main(string[] args) { System.out.println("hello, world"); } }

public static void main(string[] args) { System.out.println(hello, world); } } Java in 21 minutes hello world basic data types classes & objects program structure constructors garbage collection I/O exceptions Strings Hello world import java.io.*; public class hello { public static

More information

CMSC 202H. ArrayList, Multidimensional Arrays

CMSC 202H. ArrayList, Multidimensional Arrays CMSC 202H ArrayList, Multidimensional Arrays What s an Array List ArrayList is a class in the standard Java libraries that can hold any type of object an object that can grow and shrink while your program

More information

Mathematics. Steps to Success. and. Top Tips. Year 5

Mathematics. Steps to Success. and. Top Tips. Year 5 Pownall Green Primary School Mathematics and Year 5 1 Contents Page 1. Multiplication and Division 3 2. Positive and Negative Numbers 4 3. Decimal Notation 4. Reading Decimals 5 5. Fractions Linked to

More information