CSE114 Spring 2016 Exercises

Size: px
Start display at page:

Download "CSE114 Spring 2016 Exercises"

Transcription

1 CSE4 Spring 206 Exercises Chen-Wei Wang. Consider the following Java code: System.out.println("50 / 4 is " + 50 / 4); 2 System.out.println("50 % 4 is " + 50 % 4); Write the exact output to the console from the above two print statements. Modify Line of the above Java code, so that it will calculate and print the result with more precision (i.e., 2.5). 2. Consider the following Java code: double d = ; 2 System.out.println("d is " + d); 3 double d2 = d; 4 System.out.println("d2 is " + d2); 5 int i = (int) d; 6 System.out.println("i is " + i); 7 d2 = i * 5; 8 System.out.println("d2 is " + d2); Write the exact output to the console from the above four print statements. 3. Write a program that accomplishes the following tasks: Prompt the user for the length of a rectangle (which may be a fractional number). Prompt the user for the width of the same rectangle (which may be a fractional number). Calculate the circumference and area of the rectangle accordingly. Output to the console about the calculated circumference and area. Here is an example run of the program (where user-typed input values are put in boldface): Enter the length: 2.2 Enter the width: 4.0 A rectangle with length 2.2 and width 4.0 has circumference 2.4 and area Consider the following fragment of Java code: System.out.println("Enter a positive radius value:"); double radius = input.nextdouble(); double circumference = 0; if (radius < 0) System.out.println("Error: negative radius value!"); else circumference = 2 * 3.4 * radius; System.out.println("Circumference is " + circumference); Say the user enters -2.0 (i.e., minus two point zero) as the radius value, write down the precise output that will be generated by the above program. 5. The following fragment of Java code intends to decide the age group (i.e., child, adult, and senior) that a user falls into:

2 Scanner input = new Scanner(System.in); System.out.println("Enter your age:"); int age = input.nextint(); String agegroup = ""; /* initially no age group */ if (age < 8) { agegroup = "Child"; if (age < 65) { agegroup = "Adult"; if (age >= 65) { agegroup = "Senior"; System.out.println("our age group is " + agegroup); Say the user inputs an age value of 7. Write down the precise console output from above program. If you think the output is not correct, then suggest a fix to the above program. 6. Write, in valid Java syntax, a program which will proceed with the following 4 steps: 6. Prompt the user to enter a first integer value. If this value is positive, continue to the next step. Otherwise, print an error message and the program should terminate. 6.2 Prompt the user to enter a second integer value. If this value is positive, continue to the next step. Otherwise, print an error message and the program should terminate. 6.3 Prompt the user to enter a third integer value. If this value is positive, continue to the next step. Otherwise, print an error message and the program should terminate. 6.4 Find and print the maximum value out of the three input values. For example, if the three numbers are, 7, and 5, then your program should print: Maximum is 5. Hints: There are two possible strategies for calculating the maximum: Strategy : Choose the first number as the (temporary) maximum. Update this maximum value if you find that the second number is actually larger. Similarly, update this maximum value if you find that the third number is actually larger. Strategy 2: Compare the first and second numbers, then choose the larger one to compare against the third number, then whichever that is larger is the maximum. Here are 4 expected runs of your program (where user input values are displayed in bold face): - Error: first integer is negative. Enter the second integer value: - Error: second integer is negative. Enter the second integer value: 7 Enter the third integer value: - Error: third integer is negative. Enter the second integer value: 7 Enter the third integer value: 2

3 5 Maximum is 5 7. Consider the following fragment of Java code and write down its precise output to the console. for(int i = 2; i < 3; i ++) { if(i % 2 == 0 i > ) { System.out.println("i: " + i + "; " + "2i: " + 2 * i); else { System.out.println("i: " + i + "; " + "3i: " + 3 * i); 8. Consider the following fragment of Java code and write down its precise output to the console. Be cautious about the starting value of the loop counter j. for(int i = 0; i < 4; i ++) { for(int j = i; j < 4; j ++) { System.out.println("(" + i + ", " + j + ")"); 9. Assume that the variable a is declared as an integer array: int[] a = new int[size]; /* size is entered by the user */ ou are asked to write a fragment of Java program to determine if for each element in array a, its right neighbour, if any, is exactly one larger. For example, if a is {2, 3, 4, 5, 6, then your program should print es. If a is {2, 3, 5, 6, 7, where the right neighbour of 3 is two larger, then your program should print o. ou are asked to write two versions of the program. For Version, you must use a for loop, and your loop must always iterate through the entire array. That is, you loop must not exit early even if an element is already found not being one larger than its left neighbour. For Version 2, you must use a while loop, and your loop must exit as soon as a right neighbour is found not being one larger. Consider using a Boolean variable in the stay condition of the while loop. ou are not allowed to use either break or System.exit(0) to exit the loop.. Consider the following fragment of Java code, which checks to see if array a of integers has each number being two larger than its left neighbour. int[] a = {, 3, 5, 7, 9, ; 2 boolean rightistwolargerthanleft = true; 3 for(int i = 0; i < a.length; i ++) { 4 rightistwolargerthanleft = 5 rightistwolargerthanleft && a[i] + 2 == a[i + ]; 6 7 System.out.print("Every number is two larger than its left neighbour: "); 8 System.out.println(rightIsTwoLargerThanLeft); The above Java code compiles but it will cause a runtime ArrayIndexOutOfBoundException, which means that at some point the array a is referenced using an invalid index value. Clearly explain how this happens and suggest a proper fix to the above code.. Consider the following fragment of Java code, which checks to see if array a of integers has multiples of 3 only. int[] a = {, 2, 3, 4, 5; 2 boolean allmultiplesofthree = true; 3 for(int i = 0; i < a.length; i ++) { 4 allmultiplesofthree = a[i] % 3 == 0; 3

4 5 6 System.out.print("All numbers in a are multiples of 3: "); 7 System.out.println(allMultiplesOfThree); The above Java code compiles but contains a logical error. More precisely, it does not always work. Clearly explain under what circumstances will the above Java code work and not work. Also give examples (like Line ) to support your explanations. 2. Consider the following fragment of Java code, which repeatedly prints out Hello! until the user requests to stop: boolean userwantstocontinue = true; 2 Scanner input = new Scanner(System.in); 3 while (userwantstocontinue) { 4 System.out.println("Hello!"); 5 System.out.println("Would you like to stop printing? (/)"); 6 String answer = input.nextline(); 7 boolean stoprequested = answer.equals(""); 8 if (stoprequested == true) { /* user wants to stop */ 9 userwantscontinue = false; else { /* user does not want to stop */ 2 userwantscontinue = true; 3 4 Lines 8 to 3 can indeed be simplified into one single line. In valid Java syntax, write that single line. 3. Write a program which will: 3. Keep prompting the user for an integer value. After each prompt, the program asks if the user would like to enter another integer value. 3.2 When the user answers that they do not wish to enter another integer value, your program must print out: a) the numbers being entered so far; b) the maximum and second maximum numbers of the numbers. For a), start with a left angle bracket (<), place a comma (,) between numbers, and end with a right angle bracket (>). Hint for b): declare a variable for the maximum and another variable for the second maximum, and while inspecting the list of numbers, update them when necessary. ote that the user-entered values might be negative, so initializing these two variables as 0 would not work. ou can assume that the user will enter no more than 20 numbers. In case the user enters fewer than 2 numbers, then you should report an error saying that there is no second maximum. 3.3 After performing a) and b), you program must ask if the user would like to enter another list of numbers. If so, then repeat steps and 2. Otherwise, terminate the program and print Bye!. Here is a sample expected run of your program (where user input values are displayed in bold face): Error: too few numbers to infer the 2nd maximum. Would you like to enter another sequence of numbers (/)? 5 4

5 2 The numbers you entered: <, 5, 2> The maximum is 2. The second maximum is. Would you like to enter another sequence of numbers (/)? Bye! 4. Assume that the variable a is declared and initialized as a non-empty, two-dimensional integer array, where the number of rows is not necessarily equal to the number of columns. Write a fragment of Java code which determines: ) which row (between 0 and r - ) in array a has the minimum sum; and 2) what that minimum sum is. For example, if a is initialized as { {, 2, 3, 4, 5, /* sum: 5 */ {-, 3, 8, /* sum: */ {-, 20, 3, 9, 8 /* sum: 30 */ then your program must print Row has the minimum sum. ote, each element in the 2-D array may be negative, zero, or positive. 5. Write a fragment of Java code which determines if all elements in a 2-D array a are multiples of 3 (i.e., dividing each array element by 3 results in a remainder of 0). For example, for the following example of array a { {, 2, 3, 4, 5, /* sum: 5 */ {-, 3, 8, /* sum: */ {-, 20, 3, 9, 8 /* sum: 30 */ your program must print ot all elements are multiples of Consider the following fragment of Java code, which use two nested while loops: the outer while loop keeps prompting the user to enter a new list of integer values, whereas the inner while loop keeps prompting the user to enter a new integer value of the current list. In Line 3, we assume that the user will not enter more than three integer values for each list. import java.util.scanner; 2 public class RepeatedlyPromptTheUserForumbers { 3 public static void main(string[] args) { 4 Scanner input = new Scanner(System.in); 5 int[] numbers = new int[3]; 6 int howmanyumbersread = 0; 7 boolean userwantstoenteranotherlist = true; 8 while(userwantstoenteranotherlist) { 9 boolean userwantstoenteraewint = true; while (userwantstoenteraewint) { System.out.println(""); 2 int n = input.nextint(); 3 input.nextline(); 4 numbers[howmanyumbersread] = n; 5 howmanyumbersread ++; 6 System.out.println("ou just entered: " + n); 7 System.out.println("Would you like to enter another new int? (/)"); 8 String answer = input.nextline(); 9 userwantstoenteraewint = answer.equals(""); 20 /* end inner while loop */ 2 System.out.println("ou have entered " + howmanyumbersread + " numbers"); 5

6 22 System.out.println("Would you like to enter another list? (/)"); 23 String answer2 = input.nextline(); 24 userwantstoenteranotherlist = answer2.equals(""); 25 /* end outer while loop */ 26 /* end main method */ 27 /* end class */ However, the following run of the above Java code causes a runtime ArrayIndexOutOfBoundException exception: ou just entered: Would you like to enter another new int? (/) 20 ou just entered: 20 Would you like to enter another new int? (/) 30 ou just entered: 30 Would you like to enter another new int? (/) ou have entered 3 numbers Would you like to enter another list? (/) 5 Exception in thread "main" java.lang.arrayindexoutofboundsexception: 3 at RepeatedlyPromptTheUserForumbers.main(RepeatedlyPromptTheUserForumbers.java:64) our tasks for this exercise are to: ) explain why the above run caused ArrayIndexOutOfBoundException; and 2) suggest a proper fix to resolve the problem. Hint: Lines 5 and 6 in the above Java code are somehow misplaced. 7. Maximum Values Write a program that keeps prompting users to enter integers until they do not want to enter a new number. 7. When the user finishes entering numbers, if there are at least two numbers being entered, then determine the maximum and second maximum numbers from the list. For example, if the user enters 2, 5,, 9, then the maximum is 9 and second maximum is When the user finishes entering numbers, if there are at least three numbers being entered, then determine the maximum, second maximum, and third maximum numbers from the list. For example, if the user enters 2, 5,, 9, then the maximum is 9, second maximum is 5, and third maximum is 2. Question: ou will need to define variables like max, secondmax, and thirdmax. What should be their initial values? Would it be problematic if you simply assign them to 0 s? Hint: What if all user-entered numbers are negative? 8. umerical Palindromes 8. Write a program that keeps prompting users to enter integers until they do not want to enter a new number. When the user finishes entering numbers, determine if the list of numbers they enter read the same both forward and backward. For example, if the list of numbers they enter is 5 or, 2, 3, 3, 2,, then reading it forward and backward gives you the same list. On the other hand,, 2, 3, 4 does not read the same forward and backward. 6

7 2 ou entered <, 2, >, which does read the same forward and backward! Hint: Once storing the list of user-entered integers into an array a, create another array (of the same size) a2 that stores the elements of a in the reverse order (by scanning a backwards), then compare if a and a2 contain identical elements at all positions. 8.2 Extend your program so that it allows the user to enter another list of numbers to be determined if it is a palindrome. For example: ou entered <>, which does read the same forward and backward! Would you like to enter another list of numbers? 2 ou entered <, 2>, which does OT read the same forward and backward! Would you like to enter another list of numbers? Bye! 7

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

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

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

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

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

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

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

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

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

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

(Eng. Hayam Reda Seireg) Sheet Java

(Eng. Hayam Reda Seireg) Sheet Java (Eng. Hayam Reda Seireg) Sheet Java 1. Write a program to compute the area and circumference of a rectangle 3 inche wide by 5 inches long. What changes must be made to the program so it works for a rectangle

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

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

COSC 1020 3.0 Introduction to Computer Science I Section A, Summer 2005. Question Out of Mark A Total 16. B-1 7 B-2 4 B-3 4 B-4 4 B Total 19 Term Test #2 COSC 1020 3.0 Introduction to Computer Science I Section A, Summer 2005 Family Name: Given Name(s): Student Number: Question Out of Mark A Total 16 B-1 7 B-2 4 B-3 4 B-4 4 B Total 19 C-1 4

More information

Topic 11 Scanner object, conditional execution

Topic 11 Scanner object, conditional execution Topic 11 Scanner object, conditional execution "There are only two kinds of programming languages: those people always [complain] about and those nobody uses." Bjarne Stroustroup, creator of C++ Copyright

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

AP Computer Science Static Methods, Strings, User Input

AP Computer Science Static Methods, Strings, User Input AP Computer Science Static Methods, Strings, User Input Static Methods The Math class contains a special type of methods, called static methods. A static method DOES NOT operate on an object. This is because

More information

Using Files as Input/Output in Java 5.0 Applications

Using Files as Input/Output in Java 5.0 Applications Using Files as Input/Output in Java 5.0 Applications The goal of this module is to present enough information about files to allow you to write applications in Java that fetch their input from a file instead

More information

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

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

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

LOOPS CHAPTER CHAPTER GOALS

LOOPS CHAPTER CHAPTER GOALS jfe_ch04_7.fm Page 139 Friday, May 8, 2009 2:45 PM LOOPS CHAPTER 4 CHAPTER GOALS To learn about while, for, and do loops To become familiar with common loop algorithms To understand nested loops To implement

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 3 Lecture 3-3: Interactive Programs w/ Scanner reading: 3.3-3.4 self-check: #16-19 exercises: #11 videos: Ch. 3 #4 Interactive programs We have written programs that print

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

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq Introduction to Programming using Java wertyuiopasdfghjklzxcvbnmqwertyui

More information

Arrays. Introduction. Chapter 7

Arrays. Introduction. Chapter 7 CH07 p375-436 1/30/07 1:02 PM Page 375 Chapter 7 Arrays Introduction The sequential nature of files severely limits the number of interesting things you can easily do with them.the algorithms we have examined

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 3 Lecture 3-3: Interactive Programs w/ Scanner reading: 3.3-3.4 self-check: #16-19 exercises: #11 videos: Ch. 3 #4 Interactive programs We have written programs that print

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

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

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

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

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10) File class in Java File Input and Output (Savitch, Chapter 10) TOPICS File Input Exception Handling File Output Programmers refer to input/output as "I/O". The File class represents files as objects. The

More information

Chapter 2 Introduction to Java programming

Chapter 2 Introduction to Java programming Chapter 2 Introduction to Java programming 1 Keywords boolean if interface class true char else package volatile false byte final switch while throws float private case return native void protected break

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

Homework/Program #5 Solutions

Homework/Program #5 Solutions Homework/Program #5 Solutions Problem #1 (20 points) Using the standard Java Scanner class. Look at http://natch3z.blogspot.com/2008/11/read-text-file-using-javautilscanner.html as an exampleof using the

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

JAVA ARRAY EXAMPLE PDF

JAVA ARRAY EXAMPLE PDF JAVA ARRAY EXAMPLE PDF Created By: Umar Farooque Khan 1 Java array example for interview pdf Program No: 01 Print Java Array Example using for loop package ptutorial; public class PrintArray { public static

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

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

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

WA2099 Introduction to Java using RAD 8.0 EVALUATION ONLY. Student Labs. Web Age Solutions Inc. WA2099 Introduction to Java using RAD 8.0 Student Labs Web Age Solutions Inc. 1 Table of Contents Lab 1 - The HelloWorld Class...3 Lab 2 - Refining The HelloWorld Class...20 Lab 3 - The Arithmetic Class...25

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

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

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit. Scanner The Scanner class is intended to be used for input. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit. For example, suppose the input

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

Java Interview Questions and Answers

Java Interview Questions and Answers 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write and compile the java

More information

Object Oriented Software Design

Object Oriented Software Design Object Oriented Software Design Introduction to Java - II Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 28, 2010 G. Lipari (Scuola Superiore Sant Anna) Introduction

More information

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

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

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

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

Explain the relationship between a class and an object. Which is general and which is specific? A.1.1 What is the Java Virtual Machine? Is it hardware or software? How does its role differ from that of the Java compiler? The Java Virtual Machine (JVM) is software that simulates the execution of a

More information

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be... What is a Loop? CSC Intermediate Programming Looping A loop is a repetition control structure It causes a single statement or a group of statements to be executed repeatedly It uses a condition to control

More information

Visual Logic Instructions and Assignments

Visual Logic Instructions and Assignments Visual Logic Instructions and Assignments Visual Logic can be installed from the CD that accompanies our textbook. It is a nifty tool for creating program flowcharts, but that is only half of the story.

More information

Basics of Java Programming Input and the Scanner class

Basics of Java Programming Input and the Scanner class Basics of Java Programming Input and the Scanner class CSC 1051 Algorithms and Data Structures I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 4 Lecture 4-1: Scanner; if/else reading: 3.3 3.4, 4.1 Interactive Programs with Scanner reading: 3.3-3.4 1 Interactive programs We have written programs that print console

More information

Object Oriented Software Design

Object Oriented Software Design Object Oriented Software Design Introduction to Java - II Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa September 14, 2011 G. Lipari (Scuola Superiore Sant Anna) Introduction

More information

Install Java Development Kit (JDK) 1.8 http://www.oracle.com/technetwork/java/javase/downloads/index.html

Install Java Development Kit (JDK) 1.8 http://www.oracle.com/technetwork/java/javase/downloads/index.html CS 259: Data Structures with Java Hello World with the IntelliJ IDE Instructor: Joel Castellanos e-mail: joel.unm.edu Web: http://cs.unm.edu/~joel/ Office: Farris Engineering Center 319 8/19/2015 Install

More information

13 File Output and Input

13 File Output and Input SCIENTIFIC PROGRAMMING -1 13 File Output and Input 13.1 Introduction To make programs really useful we have to be able to input and output data in large machinereadable amounts, in particular we have to

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

Chapter 2 Elementary Programming

Chapter 2 Elementary Programming Chapter 2 Elementary Programming 2.1 Introduction You will learn elementary programming using Java primitive data types and related subjects, such as variables, constants, operators, expressions, and input

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

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

QUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall-2015 1

QUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall-2015 1 QUIZ-II Write a program that mimics a calculator. The program should take as input two integers and the operation to be performed. It should then output the numbers, the operator, and the result. (For

More information

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

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 BSc (Hons) in Computer Applications, BSc (Hons) Computer Science with Network Security, BSc (Hons) Business Information Systems & BSc (Hons) Software Engineering Cohort: BCA/07B/PT - BCA/06/PT - BCNS/06/FT

More information

Line-based file processing

Line-based file processing Line-based file processing reading: 6.3 self-check: #7-11 exercises: #1-4, 8-11 Hours question Given a file hours.txt with the following contents: 123 Kim 12.5 8.1 7.6 3.2 456 Brad 4.0 11.6 6.5 2.7 12

More information

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

Handout 3 cs180 - Programming Fundamentals Spring 15 Page 1 of 6. Handout 3. Strings and String Class. Input/Output with JOptionPane. Handout 3 cs180 - Programming Fundamentals Spring 15 Page 1 of 6 Handout 3 Strings and String Class. Input/Output with JOptionPane. Strings In Java strings are represented with a class type String. Examples:

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

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

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

Using Two-Dimensional Arrays

Using Two-Dimensional Arrays Using Two-Dimensional Arrays Great news! What used to be the old one-floor Java Motel has just been renovated! The new, five-floor Java Hotel features a free continental breakfast and, at absolutely no

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

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

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

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

CompSci 125 Lecture 08. Chapter 5: Conditional Statements Chapter 4: return Statement CompSci 125 Lecture 08 Chapter 5: Conditional Statements Chapter 4: return Statement Homework Update HW3 Due 9/20 HW4 Due 9/27 Exam-1 10/2 Programming Assignment Update p1: Traffic Applet due Sept 21 (Submit

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

Programmierpraktikum

Programmierpraktikum Programmierpraktikum Claudius Gros, SS2012 Institut für theoretische Physik Goethe-University Frankfurt a.m. 1 of 21 10/16/2012 09:29 AM Java - A First Glance 2 of 21 10/16/2012 09:29 AM programming languages

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

CASCADING IF-ELSE. Cascading if-else Semantics. What the computer executes: What is the truth value 1? 3. Execute path 1 What is the truth value 2?

CASCADING IF-ELSE. Cascading if-else Semantics. What the computer executes: What is the truth value 1? 3. Execute path 1 What is the truth value 2? CASCADING IF-ELSE A cascading if- is a composite of if- statements where the false path of the outer statement is a nested if- statement. The nesting can continue to several levels. Cascading if- Syntax

More information

VHDL Test Bench Tutorial

VHDL Test Bench Tutorial University of Pennsylvania Department of Electrical and Systems Engineering ESE171 - Digital Design Laboratory VHDL Test Bench Tutorial Purpose The goal of this tutorial is to demonstrate how to automate

More information

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements 9 Control Statements 9.1 Introduction The normal flow of execution in a high level language is sequential, i.e., each statement is executed in the order of its appearance in the program. However, depending

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

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system. http://www.tutorialspoint.com/java/java_quick_guide.htm JAVA - QUICK GUIDE Copyright tutorialspoint.com What is Java? Java is: Object Oriented Platform independent: Simple Secure Architectural- neutral

More information

Statements and Control Flow

Statements and Control Flow Contents 1. Introduction 2. Types and Variables 3. Statements and Control Flow 4. Reading Input 5. Classes and Objects 6. Arrays 7. Methods 8. Scope and Lifetime 9. Utility classes 10. Introduction to

More information

COMP 250 Fall 2012 lecture 2 binary representations Sept. 11, 2012

COMP 250 Fall 2012 lecture 2 binary representations Sept. 11, 2012 Binary numbers The reason humans represent numbers using decimal (the ten digits from 0,1,... 9) is that we have ten fingers. There is no other reason than that. There is nothing special otherwise about

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

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

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

Preet raj Core Java and Databases CS4PR. Time Allotted: 3 Hours. Final Exam: Total Possible Points 75 Preet raj Core Java and Databases CS4PR Time Allotted: 3 Hours Final Exam: Total Possible Points 75 Q1. What is difference between overloading and overriding? 10 points a) In overloading, there is a relationship

More information

Data Structures and Algorithms Written Examination

Data Structures and Algorithms Written Examination Data Structures and Algorithms Written Examination 22 February 2013 FIRST NAME STUDENT NUMBER LAST NAME SIGNATURE Instructions for students: Write First Name, Last Name, Student Number and Signature where

More information

CS114: Introduction to Java

CS114: Introduction to Java CS114: Introduction to Java Fall 2015, Mon/Wed, 5:30 PM - 6:45 PM Instructor: Pejman Ghorbanzade to Assignment 4 Release Date: Nov 04, 2015 at 5:30 PM Due Date: Nov 18, 2015 at 5:30 PM Question 1 An n

More information

VB.NET Programming Fundamentals

VB.NET Programming Fundamentals Chapter 3 Objectives Programming Fundamentals In this chapter, you will: Learn about the programming language Write a module definition Use variables and data types Compute with Write decision-making statements

More information

LAB4 Making Classes and Objects

LAB4 Making Classes and Objects LAB4 Making Classes and Objects Objective The main objective of this lab is class creation, how its constructer creation, object creation and instantiation of objects. We will use the definition pane to

More information

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void 1. Explain C tokens Tokens are basic building blocks of a C program. A token is the smallest element of a C program that is meaningful to the compiler. The C compiler recognizes the following kinds of

More information

Java Crash Course Part I

Java Crash Course Part I Java Crash Course Part I School of Business and Economics Institute of Information Systems HU-Berlin WS 2005 Sebastian Kolbe skolbe@wiwi.hu-berlin.de Overview (Short) introduction to the environment Linux

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

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

Programming Fundamentals I CS 110, Central Washington University. November 2015 Programming Fundamentals I CS 110, Central Washington University November 2015 Next homework, #4, was due tonight! Lab 6 is due on the 4 th of November Final project description + pseudocode are due 4th

More information

6. Control Structures

6. Control Structures - 35 - Control Structures: 6. Control Structures A program is usually not limited to a linear sequence of instructions. During its process it may bifurcate, repeat code or take decisions. For that purpose,

More information

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

5.2 Q2 The control variable of a counter-controlled loop should be declared as: a.int. b.float. c.double. d.any of the above. ANS: a. int. Java How to Program, 5/e Test Item File 1 of 5 Chapter 5 Section 5.2 5.2 Q1 Counter-controlled repetition requires a.a control variable and initial value. b.a control variable increment (or decrement).

More information

Computer Science 217

Computer Science 217 Computer Science 217 Midterm Exam Fall 2009 October 29, 2009 Name: ID: Instructions: Neatly print your name and ID number in the spaces provided above. Pick the best answer for each multiple choice question.

More information

Chapter One Introduction to Programming

Chapter One Introduction to Programming Chapter One Introduction to Programming 1-1 Algorithm and Flowchart Algorithm is a step-by-step procedure for calculation. More precisely, algorithm is an effective method expressed as a finite list of

More information

Computers. An Introduction to Programming with Python. Programming Languages. Programs and Programming. CCHSG Visit June 2014. Dr.-Ing.

Computers. An Introduction to Programming with Python. Programming Languages. Programs and Programming. CCHSG Visit June 2014. Dr.-Ing. Computers An Introduction to Programming with Python CCHSG Visit June 2014 Dr.-Ing. Norbert Völker Many computing devices are embedded Can you think of computers/ computing devices you may have in your

More information

D06 PROGRAMMING with JAVA

D06 PROGRAMMING with JAVA Cicles Formatius de Grau Superior Desenvolupament d Aplicacions Informàtiques D06 PROGRAMMING with JAVA Ch8 Arrays and Array Lists PowerPoint presentation, created by Angel A. Juan - ajuanp(@)gmail.com,

More information

Pseudo code Tutorial and Exercises Teacher s Version

Pseudo code Tutorial and Exercises Teacher s Version Pseudo code Tutorial and Exercises Teacher s Version Pseudo-code is an informal way to express the design of a computer program or an algorithm in 1.45. The aim is to get the idea quickly and also easy

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

Java Cheatsheet. http://introcs.cs.princeton.edu/java/11cheatsheet/ Tim Coppieters Laure Philips Elisa Gonzalez Boix

Java Cheatsheet. http://introcs.cs.princeton.edu/java/11cheatsheet/ Tim Coppieters Laure Philips Elisa Gonzalez Boix Java Cheatsheet http://introcs.cs.princeton.edu/java/11cheatsheet/ Tim Coppieters Laure Philips Elisa Gonzalez Boix Hello World bestand genaamd HelloWorld.java naam klasse main methode public class HelloWorld

More information

Writing Control Structures

Writing Control Structures Writing Control Structures Copyright 2006, Oracle. All rights reserved. Oracle Database 10g: PL/SQL Fundamentals 5-1 Objectives After completing this lesson, you should be able to do the following: Identify

More information