ITI 1120 Lab #7. Agenda Topics in this lab: –Methods & Arrays –Library classes –Testing (JUnit) –Strings In this lab, you are going to create your own.

Slides:



Advertisements
Similar presentations
Escape Sequences \n newline \t tab \b backspace \r carriage return
Advertisements

JavaScript I. JavaScript is an object oriented programming language used to add interactivity to web pages. Different from Java, even though bears some.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 9 Strings.
Computer Programming w/ Eng. Applications
Computer Science 209 Software Development Equality and Comparisons.
MSc IT Programming Methodology (2). number name number.
Chapter 7 Strings F To process strings using the String class, the StringBuffer class, and the StringTokenizer class. F To use the String class to process.
1 Strings and Text I/O. 2 Motivations Often you encounter the problems that involve string processing and file input and output. Suppose you need to write.
Chapter 7 Strings F Processing strings using the String class, the StringBuffer class, and the StringTokenizer class. F Use the String class to process.
Strings An extension of types A class that encompasses a character array and provides many useful behaviors Chapter 9 Strings are IMMUTABLE.
Chapter 41 Variables and JSP Control Structures JavaServer Pages By Xue Bai.
1 Various Methods of Populating Arrays Randomly generated integers.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
T ESTING WITH J UNIT IN E CLIPSE Farzana Rahman. I NTRODUCTION The class that you will want to test is created first so that Eclipse will be able to find.
©2004 Brooks/Cole Chapter 7 Strings and Characters.
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
CIT 590 Intro to Programming Java lecture 3. Hashmaps The equivalent of python dictionaries. With both ArrayLists and Hashmaps, the syntax only allows.
Strings and Arrays The objectives of this chapter are:  To discuss the String class and some of its methods  To discuss the creation and use of Arrays.
Chapter 10.
Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types.
Writing a Unit test Using JUnit At the top of the file include: import junit.framework.TestCase; The main class of the file must be: public Must extend.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
Chapter 7: User-Defined Methods
COMP 110 Introduction to Programming Mr. Joshua Stough September 10, 2007.
Sanjay Goel, School of Business, University at Albany, SUNY 1 MSI 692: Special Topics in Information Technology Lecture 4: Strings & Arrays Sanjay Goel.
CS 106 Introduction to Computer Science I 10 / 16 / 2006 Instructor: Michael Eckmann.
1 The First Step Learning objectives write Java programs that display text on the screen. distinguish between the eight built-in scalar types of Java;
Fundamentals of Python: From First Programs Through Data Structures
Week #2 Java Programming. Enable Line Numbering in Eclipse Open Eclipse, then go to: Window -> Preferences -> General -> Editors -> Text Editors -> Check.
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
© Dr. A. Williams, Fall Present Software Quality Assurance – JUnit Lab 1 JUnit A unit test framework for Java –Authors: Erich Gamma, Kent Beck Objective:
Fundamentals of Python: First Programs
by Chris Brown under Prof. Susan Rodger Duke University June 2012
1 Lab Session-III CSIT-120 Fall 2000 Revising Previous session Data input and output While loop Exercise Limits and Bounds Session III-B (starts on slide.
Recitation 2 Main Method, API & Packages, Java Basics.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
The string data type String. String (in general) A string is a sequence of characters enclosed between the double quotes "..." Example: Each character.
Characters The data type char represents a single character in Java. –Character values are written as a symbol: ‘a’, ‘)’, ‘%’, ‘A’, etc. –A char value.
The Java Programming Language
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
What is an Array? An array is a collection of variables. Arrays have three important properties: –group of related items(for example, temperature for.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
1 Arrays An array is a collection of data values, all of which have the same type. The size of the array is fixed at creation. To refer to specific values.
String Manipulation Chapter 15 This chapter explains the String facilities. You have already seen some of the main methods of the String class.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
30/10/ Iteration Loops Do While (condition is true) … Loop.
Introduction to Java Java Translation Program Structure
ITI 1120 Lab #5 Contributors: S. Boyd, R. Plesa, A. Felty, D. Inkpen, A. Williams, D. Amyot.
Vladimir Misic: Characters and Strings1Tuesday, 9:39 AM Characters and Strings.
String Processing Word processing term papers, writing memoirs, sending messages, responding to surveys, placing online orders and registering products.
Coding Bat: Ends in ly Given a string of even length, return a string made of the middle two chars, so the string "string" yields "ri". The string.
Repetition. Loops Allows the same set of instructions to be used over and over again Starts with the keyword loop and ends with end loop. This will create.
1 Romelia Plesa, Alan Williams, Sylvia Boyd, Daniel Amyot, Diana Inkpen, Gilbert Arbez, Mohamad Eid ITI 1120 Lab #3.
Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 1 Introduction An array is a collection of identical boxes.
CSCI 1226 FALL 2015 MIDTERM #1 REVIEWS.  Types of computers:  Personal computers  Embedded systems  Servers  Hardware:  I/O devices: mice, keyboards,
1 Predefined Classes and Objects Chapter 3. 2 Objectives You will be able to:  Use predefined classes available in the Java System Library in your own.
Software Design– Unit Testing SIMPLE PRIMER ON Junit Junit is a free simple library that is added to Eclipse to all automated unit tests. The first step,
Chapter 5: Arrays in Java. The objectives of this chapter are:  1. To discuss the creation and use of Arrays.   2. To continue to use the String class.
CSCI 51 Introduction to Programming Dr. Joshua Stough February 24, 2009.
Chapter 8: Loops, Arrays, Strings Loop statements –do –while –for Arrays –declaration, allocation, initialization, access –multi-dimensional –heterogeneous.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Chapter 15 Running Time Analysis. Topics Orders of Magnitude and Big-Oh Notation Running Time Analysis of Algorithms –Counting Statements –Evaluating.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
4. Java language basics: Function
Java Programming: From Problem Analysis to Program Design, 3e Chapter 7 User-Defined Methods.
2.5 Another Java Application: Adding Integers
IDENTIFIERS CSC 111.
Working with Text and Numbers in Java
Do While (condition is true) … Loop
Presentation transcript:

ITI 1120 Lab #7

Agenda Topics in this lab: –Methods & Arrays –Library classes –Testing (JUnit) –Strings In this lab, you are going to create your own library class, and then learn how to create and run tests on the methods in your class.

Java Methods & Arrays Every method in Java has – a return type – a name – a parameter list – a body Return type: It specifies what is the type of the result of the method. If there is no result, this type is void. Name: The same as the name of an algorithm. Parameter list: It specifies the name and the type of the parameters, in order. Body: The same as the body of an algorithm, but it must follow the rules of the language so that the computer understands it.

Example Method public static double [] myMethod(int [] a, int b, int c) { // DECLARE VARIABLES/DATA DICTIONARY // the result double [] r = new double [] {1.5, 2.5, 3.4}; // BODY OF ALGORITHM r[1] = a[0] + b +c; // RETURN RESULT return r; /*return reference to array*/ } Method nameReturn type expression (value to return) Array can be passed as parameters (references to existing arrays) or returned from methods (need to allocate memory for a new array). Parameter list

Main method public static void main (String[] args) { int i; int [] x = new int [] {1, 2, 3, 4, 5}; double [] result; result = myMethod( x, 6, 9); for (i = 0; i < result.length; i++) System.out.print(result[i] + " "); System.out.println(); }

A library class Create a class called MyMath, that implements the following methods, WITHOUT using the Math class from the Java software development kit. 1.A method that returns the absolute value of an integer x. 2.A method that calculates x y for integers x and y. Use a loop the multiplies x by itself y times. Assume y ≥ 0

The absolute value algorithm GIVENS:X(an integer) RESULT:AbsX(the absolute value of X) HEADER:AbsX  Abs( X ) BODY: X  0 AbsX  – XAbsX  X false true

The exponentiation algorithm GIVENS:X, Y(two integers) RESULT:XToY(the value of X Y ) INTERMEDIATES:Count(counts times X has been multiplied by itself) HEADER: XToY  Pow( X, Y ) BODY: Count ≤ Y XToY  XToY  X Count  Count + 1 false true XToY  1 Count  1

A main method for the library class Write a main method for class MyMath that will do the following: 1.Read the values a and b from the keyboard. 2.Calls the method abs() with the parameter a, and saves the result in the variable absA. 3.Calls the method pow() with the parameters a and b, and saves the result in the variable aToB. 4.Prints the values absA and aToB along with suitable messages.

Testing We’re now going to do some testing of the methods in the class MyMath. When doing testing: 1.Call a method with some test values as the parameters. 2.Observe the results. 3.See if the results are as expected. This means that you need to choose some test values for which you can determine the expected results using some other means.

Manual Testing Try testing your class by running the main method and typing various values for x and y. –Choose your values carefully, to try and take different paths through the code. For the absolute value method: –try values of x that are less than zero, equal to zero, and greater than zero. For the exponentiation method: –try y = 0, y = 1, y > 1 –try x 1

Testing with JUnit JUnit is a set of classes that you can add to the Java software development kit to make testing easier. JUnit was coined from “Java unit”. –Unit testing is when you testing parts of a complete application, such as methods in library classes. More information: –

Key JUnit concepts Test verdict: each test case can pass (green) or fail (red). Test case: an experiment to see if a method produces the correct result for a set of parameter values. –Consists of a method contained in a test class. –You can add as many methods as you wish in a test class. Test class: contains a set of test cases for a class. –Usually, there is a corresponding test class for each class you want to test.

Setting up a test class Be sure that your MyMath class is already loaded into Dr. Java In Dr. Java, from the ‘File’ menu, select “Create new JUnit test case…” You will be asked for the name of the test class. Enter MyMathTest. –It is important to include the word “Test” as part of the class name; this is how JUnit knows how to find test classes. The result should look similar to the code on the next slide.

The test class import junit.framework.TestCase; /** * A JUnit test case class. * Every method starting with the word "test" will be called * when running the test with JUnit. */ public class MyMathTest extends TestCase { /** * A test method. * (Replace "X" with a name describing the test. You may * write as many "testSomething" methods in this class as * you wish, and each one will be called when running * JUnit over this class.) */ public void testX() { }

Features of the test class import junit.framework.TestCase; –We will use the class Test case from the JUnit collection of classes. After the name of the class, there is: extends TestCase –This says that the class is going to act like a test case, as defined by JUnit. An empty test method, which returns a void result and has no parameters. –JUnit will call this method as a test case. –The method should be renamed to testXXX where XXX gives some idea of the purpose of the test case.

Creating a test method Let’s create a test for the absolute value method. The absolute value method takes one value as a parameter; we need to provide test data for that parameter. –Example: if we call abs(-4), we should get 4 as a result. –Set up 3 values: testValueX : the -4 that will be the test data for our method. expected : the result we expect: 4 actual : the result that abs(-4) actually returns to us.

Checking the result An important part of testing is checking that the result you get matches what you expect. The result is a verdict: pass or fail. With JUnit, there is a method in the Assert class called Assert.assertEquals( expected, actual ) –If the two values expected and actual are equal, the method will return and execution will continue. –If the values are not equal, the test case will be declared to have failed at this point. Execution of the test method stops. If you reach the end of a test method, and no failures have occurred, the test will be declared to have passed.

The assertEquals method There are several versions of the assertEquals method, so that you can test values of various types –The expected value is always the first parameter, and the actual value is always the second parameter Assert.assertEquals( int, int ) Assert.assertEquals( char, char ) Assert.assertEquals( boolean, boolean ) Assert.assertEquals( String, String ) Assert.assertEquals( double, double, double ) –Testing equality of double variables is a special case; remember that you should compare that they are “sufficiently close” to each other. –The third parameter specifies the maximum difference to accept as equal (a number like )

Enter a test method Replace the empty testX method with the following: public void testAbsNegative() { // Purpose: test that abs() works for a value < 0. int testValueX;// Test data for calling method int expected;// Value we expect to see as result int actual; // Actual value that method returns testValueX = -4; expected = 4; actual = MyMath.abs( testValueX ); Assert.assertEquals( expected, actual ); }

One more addition Add the following at the top of your test class: import junit.framework.Assert; This is so we can use the assertEquals method from the JUnit class Assert.

Compiling the tests Be sure that you have both of the classes Math and MyMath loaded into Dr. Java. Click the ‘Compile’ button. After a few seconds, the ‘Test’ button should be enabled.

Running the Tests Click the “Test” button. Test report Test button Pass/ fail bar

Results from JUnit JUnit always shows a coloured bar after a test run: –Green: all tests passed –Red: at least one test failed. –[JUnit slogan: “Keep the bar green to keep the code clean.”] You also get a test report that lists any failure messages.

Adding a test that will fail Create a second test by adding another method to the test class. This time, we deliberately want the test to fail, just to see what happens. –Call abs(4) and expect -4 as a result (which is wrong!)

Result from a test failure

The test report MyMathTest testAbsNegative testAbsPositive File: C:\...\MyMathTest.java [line: 39] Failure: expected: but was: A test name shown in green has passed; one shown in red has failed. For each failure, you get –The line number in the test case where the failure occurred. –A report from JUnit as to the result of the comparison The values are enclosed in <> in case you need to check for extra spaces, etc.

Try creating the following test methods Absolute value –test data: 0 –test data: >= 1 Exponentiation: –x > 1, x = 1, x = 0, x < 0 –y = 0, y = 1, y > 1

Interactions and Dr. Java An extra feature of Dr. Java is that it lets you call methods directly in the “interactions” area, after a class has been compiled. For example: –Type MyMath.abs(-4) into the Interactions area. Dr. Java will call the method abs in the MyMath class directly, with the value -4 as the parameter. The value that is returned is displayed in the Interactions area.

Using the Interactions area

More on the Interactions area You can also call methods from pre-loaded Java classes (such as Math ) directly in the interactions area. Example: the round method in the class Math, that rounds a double value to the nearest integer. –Type Math.round( 3.6 ) in the interactions area and see the result. –Try the following: Math.round( 3.4 ) Math.round( 3.5 ) Math.round( 3.0 ) Math.round( -3.4 ) Math.round( -3.6 ) Math.round( -3.5 ) (is the result what you expected?)

Extra exercises Add the following mathematical methods to your class MyMath and appropriate tests in MyMathTest –square(int n) – returns the square of n Create tests with n=40000 and n= What do you notice? –round(double n) – return the integer value rounded to n. Assumption: the rounded value for n can be represented with an integer between about -2 billion to + 2 billion. Note: Math.floor(x) returns a real number representing an integer less then or equal to the real x: –Math.floor(3.6) returns 3.0 –Math.floor(-3.2) returns -4.0 Examples –MyMath.floor( 3.9 ) gives 4 –MyMath.floor( 3.1 ) gives 3 –MyMath.floor( 3.5 ) gives 4 –MyMath.floor( -1.2 ) gives -1 –MyMath.floor( -1.5 ) gives -1 –MyMath.floor( -1.6 ) gives -2

String vs. char[] Similarities: –both are collections of characters –both indexed from 0 up to length - 1 –both are reference variables no == comparison!

String vs. char[] Differences: –Access of single character: str.charAt(i) vs array[i] –Strings cannot be modified internally once they are created No equivalent of array[i] = ‘x’ –String variables can be assigned constant strings where using new is optional String str; str = "abc"; str = new String("def" ); –Most operations on Strings are done with methods array.length // not a method call; no ( ) str.length( ) // method call; ( ) required

Conversions: String  char[] char[] array; char[] array2;... // Create String from array String str = new String( array ); // Create array from String array2 = str.toCharArray( );

Common Methods of String Review the various methods available in the String class: charAt(…), indexOf(…), length(…) toCharArray(…) equals(…), compareTo(…) concat(…), substring(…), toLowerCase(…), toUpperCase(…) …

Careful! For String character strings: –Use the double quotes ( " ) –Do not use: “, ”, « or » For character arrays: –Use the single quote ( ' ) –Do not use: ‘ or ’

Exercises with String and char[] Using the Dr Java Interactions window –Using String constants of you choice, try to call common methods from the String class. For example: " ".length() "12345".charAt(4) and then “12345”.indexOf('4') "minuscule".toUpperCase() "A".compareTo("a") (et and the reverse?) "happy".concat(" ").concat("holidays") String s1="ab"; String s2="ab"; s1.equals(s2) (and s1==s2 ?) String s3="thanks"; char[] tabS3= s3.toCharArray(); tabS3[0]

Extra exercises, if you feel motivated … Develop and create a method countLowerCase which counts the number of lower case characters in a String object. Test it using the Interaction Window. (More advanced) Develop and write a method reverseUpperLower which receives a String object as a parameter and exchanges lower case characters to uppercase and vice versa.