CS 101: Practice Questions for Test 2 SOLUTIONS

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

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

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

Introduction to Java. CS 3: Computer Programming in Java

MIDTERM 1 REVIEW WRITING CODE POSSIBLE SOLUTION

Basics of Java Programming Input and the Scanner class

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

Sample CSE8A midterm Multiple Choice (circle one)

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

AP Computer Science Static Methods, Strings, User Input

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

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

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:

CS170 Lab 11 Abstract Data Types & Objects

Chapter 2 Introduction to Java programming

(Eng. Hayam Reda Seireg) Sheet Java

Using Files as Input/Output in Java 5.0 Applications

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

Topic 11 Scanner object, conditional execution

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

CS 121 Intro to Programming:Java - Lecture 11 Announcements

Building Java Programs

Introduction to Java

Interactive Programs and Graphics in Java

Interactive Applications (CLI) and Math

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

Explain the relationship between a class and an object. Which is general and which is specific?

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

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

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

JAVA ARRAY EXAMPLE PDF

CS114: Introduction to Java

Inheritance, overloading and overriding

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

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

Building Java Programs

LOOPS CHAPTER CHAPTER GOALS

Object-Oriented Programming in Java

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

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

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

Introduction to Programming

Iteration CHAPTER 6. Topic Summary

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

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

Handout 3 cs180 - Programming Fundamentals Spring 15 Page 1 of 6. Handout 3. Strings and String Class. Input/Output with JOptionPane.

Homework/Program #5 Solutions

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

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

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

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

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

PIC 10A. Lecture 7: Graphics II and intro to the if statement

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

Building Java Programs

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

Java CPD (I) Frans Coenen Department of Computer Science

13 File Output and Input

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

Data Structures Lecture 1

Line-based file processing

java Features Version April 19, 2013 by Thorsten Kracht

Building Java Programs

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

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

public class Craps extends JFrame implements ActionListener { final int WON = 0,LOST =1, CONTINUE = 2;

Programmierpraktikum

The Snake Game Java Case Study

Java Cheatsheet. Tim Coppieters Laure Philips Elisa Gonzalez Boix

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

AP Computer Science Java Subset

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

Arrays. Introduction. Chapter 7

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

Assignment No.3. /*-- Program for addition of two numbers using C++ --*/

Software Testing. Definition: Testing is a process of executing a program with data, with the sole intention of finding errors in the program.

Introduction to Computer Programming, Spring Term 2014 Practice Assignment 3 Discussion

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

Comp 248 Introduction to Programming

Install Java Development Kit (JDK) 1.8

1 Hour, Closed Notes, Browser open to Java API docs is OK

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

Lab 5: Bank Account. Defining objects & classes

Object-Oriented Programming in Java

Building Java Programs

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

WRITING DATA TO A BINARY FILE

Moving from CS 61A Scheme to CS 61B Java

Java Classes. GEEN163 Introduction to Computer Programming

Chapter 1 Java Program Design and Development

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

Introduction to Java Applets (Deitel chapter 3)

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

Event-Driven Programming

Collections.sort(population); // Método de ordenamiento

Programming Languages CIS 443

College of the Holy Cross CCSCNE 06 Programming Contest Problems

Arrays in Java. Working with Arrays

D06 PROGRAMMING with JAVA

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

Transcription:

CS 101: Practice Questions for Test 2 SOLUTIONS 1. Write a Java application which prompts the user to enter integers from the screen until the end of file character is entered, computes the sum of the integers, and prints this sum to the screen. import java.util.scanner; public class SumInts{ public static void main (String[] args){ Scanner scan = new Scanner(System.in); int sum = 0; System.out.print("Enter some integers, push <CONTROL>D to exit: "); while (scan.hasnext()) sum += scan.nextint(); System.out.println("\nThe sum of your integers is " + sum); 2. If a triangle has side lengths a,b,c, then the formula for the area of the triangle is s(s a)(s b)(s c), where s = 1 (a + b + c). Write a class Triangle which contains three 2 private data members a,b,c for the side lengths. Make sure Triangle has the following methods: public Triangle (double x, double y, double z) // constructor: x,y,z are side lengths public double area () // compute and return area of triangle public double perimeter () // compute and return the perimeter of triangle

public class Triangle{ private double a,b,c; public Triangle(double x, double y, double z){ a = x; b = y; c = z; public double area(){ double s = 1./2 * (a+b+c); return Math.sqrt(s*(s-a)*(s-b)*(s-c)); public double perimeter(){ return a+b+c; 3. Bonus: The side lengths of a triangle must satisfy the following constraints: Each side must be positive, and no side may be longer than the sum of the other two side lengths. Modify your constructor Triangle above to print to the screen an appropriate error message if the proposed side lengths do not meet these specifications. Replace the above constructor with public Triangle(double x, double y, double z){ a = x; b = y; c = z; if (a<0 b<0 c<0 a+b<c a+c<b b+c<a) System.out.println("Not a valid triangle."); 4. Consider the method question4 defined by public static double question4 (double x, double y){ return (x>y)? x : y;

(a) What is the value of question4(4.7,5.3)? 5.3 (b) Describe in words what the return value of the method question4 represents mathematically in terms of the parameters x,y. The return value is the maximum of x,y, since it is x if x>y and y otherwise. 5. What is the output of the following code fragment? int z = 4; do{ System.out.println(z); z--; while (z>5); 4 6. Write a method public static String firstword(string sentence) which uses a Scanner to scan through the String sentence to return the word in the sentence which comes first alphabetically. (Recall that the method next() returns the next word in a Scanner.) public static String firstword(string sentence){ Scanner scan = new Scanner(sentence); String first = scan.next(), temp; while (scan.hasnext()){ temp = scan.next(); if ((first.touppercase()).compareto(temp.touppercase()) > 0) first = temp; return first;

7. What is the output to the screen of the following code fragment? boolean done = false; int n = 5; while (n>0 &&!done){ --n; System.out.println(n); done = (n*n==1 n<3); 4 3 2 8. Write a java applet which draws four squares of side-length 50 whose upper left corners have coordinates given by random integers from 0 to 99. import javax.swing.japplet; import java.awt.*; public class Squares extends JApplet{ public void paint (Graphics page){ final int SIDE_LENGTH = 50; for (int i=1; i<=4; i++){ int x = (int)(math.random()*100); int y = (int)(math.random()*100); page.drawrect(x,y,side_length,side_length);

public class BasketballTeam{ private int score; private String name; public BasketballTeam(String s){ score = 0; name = s; public int getscore(){ public String getname(){ return name; public String tostring(){ return ("The " + name + " have " + score + " points.\n"); public int freethrow(){ score++; public int threepoint(){ score += 3; public int makeshot(){ score += 2;

9. Consider the class BasketballTeam above. What is the output of the following driver program? public class BigGame{ public static void main(string[] args){ BasketballTeam team1 = new BasketballTeam("Raiders"); BasketballTeam team2 = new BasketballTeam("Tigers"); team1.makeshot(); team2.freethrow(); team1.threepoint(); System.out.println ("Team 1 has " + team1.freethrow() + " points."); team2.makeshot(); System.out.print(team1) System.out.print(team2); Team 1 has 6 points. The Raiders have 6 points. The Tigers have 3 points. 10. Using the BasketballTeam class above, write a driver class which simulates a basketball game in the following way: instantiate two teams as above, and then assume the teams alternate possession of the ball for 20 times each. During each possession, the team with the ball has the following probabilities: 35% chance of making a 2-point shot 15% chance of making a 3-point shot 20% chance of making a free throw 30% chance of turning over the ball without scoring Use a double variable set to equal Math.random(), together with some if-else statements, to control the probabilities. After each possession, print the score of both teams to the screen.

public class GameSimulator{ public static void main(string[] args){ BasketballTeam team1 = new BasketballTeam("Raiders"); BasketballTeam team2 = new BasketballTeam("Tigers"); for (int i=1; i<=20; i++){ double rand = Math.random(); if (rand<.35) team1.makeshot(); else if (rand<.50) team1.threepoint(); else if (rand<.70) team1.freethrow(); System.out.print(team1); System.out.print(team2); rand = Math.random(); if (rand<.35) team2.makeshot(); else if (rand<.50) team2.threepoint(); else if (rand<.70) team2.freethrow(); System.out.print(team1); System.out.print(team2);