Building Your Own Class

Slides:



Advertisements
Similar presentations
Introduction to Eclipse. Start Eclipse Click and then click Eclipse from the menu: Or open a shell and type eclipse after the prompt.
Advertisements

Introduction to the C# Programming Language for the VB Programmer.
Loops – While Loop Repetition Statements While Reading for this Lecture, L&L, 5.5.
Using ArrayList. Lecture Objectives To understand the foundations behind the ArrayList class Explore some of the methods of the ArrayList class.
Lecture Review (If-else Statement) if-else statement has the following syntax: if ( condition ) { statement1; } else { statement2; } The condition.
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;
11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
C# Tutorial From C++ to C#. Some useful links Msdn C# us/library/kx37x362.aspxhttp://msdn.microsoft.com/en- us/library/kx37x362.aspx.
Java Unit 9: Arrays Declaring and Processing Arrays.
CHAPTER 6 Loop Structures.
Computer and Programming File I/O File Input/Output Author: Chaiporn Jaikaeo, Jittat Fakcharoenphol Edited by Supaporn Erjongmanee Lecture 13.
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.
Methods (Functions) CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Microsoft Visual Basic 2008 CHAPTER NINE Using Arrays and File Handling.
Microsoft Visual Basic 2005 CHAPTER 9 Using Arrays and File Handling.
Using Arrays and File Handling
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
Arrays (Part 1) Computer Science Erwin High School Fall 2014.
Programming With Java ICS201 University Of Ha’il1 Chapter 8 Polymorphism and Abstract Classes.
File I/O 11_file_processing.ppt
REVIEW On Friday we explored Client-Server Applications with Sockets. Servers must create a ServerSocket object on a specific Port #. They then can wait.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 2.
ArrayList, Multidimensional Arrays
File I/O Static void Main( ) {... } data. Topics I/O Streams Reading and Writing Text Files Formatting Text Files Handling Stream Errors File Pointers.
Chapter 4: Loops and Files
Debugging Dwight Deugo Nesa Matic
Debugging. 2 © 2003, Espirity Inc. Module Road Map 1.Eclipse Debugging  Debug Perspective  Debug Session  Breakpoint  Debug Views  Breakpoint Types.
Lecture 3 Decisions (Conditionals). One of the essential features of computer programs is their ability to make decisions. Like a train that changes tracks.
COMPUTER PROGRAMMING. Iteration structures (loops) There may be a situation when you need to execute a block of code several number of times. In general,
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 2 – Classes and objects.
CMP-MX21: Lecture 4 Selections Steve Hordley. Overview 1. The if-else selection in JAVA 2. More useful JAVA operators 4. Other selection constructs in.
Lecture 101 CS110 Lecture 10 Thursday, February Announcements –hw4 due tonight –Exam next Tuesday (sample posted) Agenda –questions –what’s on.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.
 Prentice Hall. All rights reserved. 1 Recursion (Section 7.13 & Exercise7.40 from ed.3) (Sections 6.15, 6.16 from ed.1) Many slides modified.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
CS360 Windows Programming
Copyright © 2012 Pearson Education, Inc. Chapter 5 Loops, File, and Random Numbers.
Classes. Student class We are tasked with creating a class for objects that store data about students. We first want to consider what is needed for the.
1 CS 177 Week 11 Recitation Slides Class Design/Custom Classes.
Loops.  (No Quiz)  Hand in Assignment #1  Last chance for Q+A on the midterm  Loops 2.
Building Your Own Class. We will build a simple instance class for an inventory control application and a main program to test it. We need an Item class.
General Computer Science for Engineers CISC 106 Lecture 12 James Atlas Computer and Information Sciences 08/03/2009.
IAP C# 2011 Lecture 2: Delegates, Lambdas, LINQ Geza Kovacs.
2: Basics Basics Programming C# © 2003 DevelopMentor, Inc. 12/1/2003.
Lecture 11: Generics. The Generic List loading data from a file using System.IO; : namespace EmpListDemo { static class Program { static void Main(string[]
CS0007: Introduction to Computer Programming The for Loop, Accumulator Variables, Seninel Values, and The Random Class.
Programming in Java Transitioning from Alice. Becomes not myFirstMethod but …. public static void main (String[] arg) { // code for testing classes goes.
1 Adding a Model. We have created an MVC web app project Added a controller class. Added a view class. Next we will add some classes for managing movies.
C# Part 1 Intro to C#. Background Designed to be simple, modern, general- purpose, OO, programming language Strong type checking, array bounds checking,
Information and Computer Sciences University of Hawaii, Manoa
The need for Programming Languages
Threads in Java Two ways to start a thread
using System; namespace Demo01 { class Program
Ch 10- Advanced Object-Oriented Programming Features
Debugging Dwight Deugo
2.5 Another Java Application: Adding Integers
Chapter 5: Control Structures II
Loop Structures.
User input We’ve seen how to use the standard output buffer
Java Programming: Guided Learning with Early Objects
Important terms Black-box testing White-box testing Regression testing
Chapter 5: Control Structures II
Important terms Black-box testing White-box testing Regression testing
Advanced Programming Lecture 02: Introduction to C# Apps
An Introduction to Java – Part I, language basics
Structured Variables & File Systems
Debugging Dwight Deugo
Developing Java Applications with NetBeans
Developing Java Applications with NetBeans
LOOPS The loop is the control structure we use to specify that a statement or group of statements is to be repeatedly executed. Java provides three kinds.
Presentation transcript:

Building Your Own Class Lecture 3 Building Your Own Class

Specifications for inventoryApp We will build a simple instance class for an inventory control application and a main program to test it. We need an Item class that will hold information about each of a number of items sold by the XYZ Corporation. The Item class will hold: itemName itemNumberInStock itemRetailPrice The accessors for these three private variables will be called: GetName GetQuantity GetPrice

Creating a new Console Application inventoryApp

Adding an Instance Class

A Test Program for inventoryApp using System; namespace inventoryApp { class Program static void Main(string[] args) string name; int quantity; double price;   Console.Write("Enter item name...................................... "); name = Console.ReadLine(); Console.Write("Enter initial number of items........................ "); quantity = Convert.ToInt32(Console.ReadLine()); Console.Write("Enter retail price................................... "); price = Convert.ToDouble(Console.ReadLine()); Item myItem = new Item(name, quantity, price); Console.WriteLine("Item Name = " + myItem.GetName() + " Price = " + myItem.GetPrice()); Console.ReadKey(); }

inventoryApp Class without Accessors namespace inventoryApp { class Item private string itemName; private int itemInStock; private double itemRetailPrice;   public Item() } public Item(string iName, int iInStock, double iRetailPrice) itemName = iName; itemInStock = iInStock; itemRetailPrice = iRetailPrice;

Accessors for the inventoryApp Class public string GetName() { return itemName; }   public int GetQuantity() return itemInStock; public double GetPrice() return itemRetailPrice;

Test Run for inventoryApp (Build 0)

Extending the inventoryApp Creating and naming items individually is not efficient. We need to extend the functions of our inventoryApp to allow us to generate a list of items. For this we will introduce a generic list List<Type>. Your first task is to add a generic list of type "Item" to the main test program and load the list with mulitple items... The result of your multiple item test should look similar to the following:

Review the ShapesDemoFixed program posted on the Course Web Page for examples of how to use Generic Lists. using System; using System.Collections.Generic;   namespace ShapesDemo { public partial class FormMain : Form List<Shape> shapes = new List<Shape>(); timerAnim.Start(); } public void genShapes() for (int i = 0; i < 10; i++) shapes.Add(new Square((double)(rnd.Next(100) + 25), (double)(rnd.Next(w) - 100), (double)(rnd.Next(h) - 100), (double)rnd.Next(-1000, 1000) / 100.0, (double)rnd.Next(-100, 100) / 500.0, private void updateShapes() foreach (Shape s in shapes) s.move(); s.Bounce(picBox.Width,picBox.Height); generic list for type Shape new Squares are being Added to the list shapes the foreach( ) construct is used to look at every shape s in the list shapes.

A Simplified Version of the Main Test Program for inventoryApp Tired of retyping the data every time you run the program? Just hardwire the creation of a list of products into the main test program. This is OK here because the main program is only being used to debug the Item class. using System; using System.Collections.Generic; namespace inventoryApp { class Program static void Main(string[] args)   List <Item> items = new List<Item>(); items.Add(new Item("Widget", 10, 19.95)); items.Add(new Item("Geegaw", 100, 9.99)); items.Add(new Item("Doodad", 1000, 0.99)); foreach (Item itm in items) Console.WriteLine(itm.GetName() + " " + itm.GetQuantity() + " " + itm.GetPrice()); } Console.ReadKey(); Later we will learn how to read and write text files using C#...(see example on next slide).

Reading from a Textfile Note: This is for future reference only. You are not being asked to create a program that reads a textfile at this time. products.txt 10 19.95 Widget 100 9.99 Geegaw 1000 0.99 Doodad eof static void Main(string[] args) { string name; int quantity; double price; List <Item> items = new List<Item>();   string textline = ""; StreamReader tr = new StreamReader("products.txt"); while (true) textline = tr.ReadLine(); if (textline == "eof") break; string[] str = textline.Split(' '); quantity = int.Parse(str[0]); price = double.Parse(str[1]); name = str[2]; items.Add(new Item(name, quantity, price)); } tr.Close(); foreach (Item itm in items) Console.WriteLine(itm.GetName() + " " + itm.GetQuantity() + " " + itm.GetPrice()); Console.ReadKey(); This text file is placed in the Debug directory of the project along with the executable (.exe) program.

Next Iteration We are continuing to build our Item.cs class. In the next iteration, add methods to perform the following operations on an item: Submit the updated version of your Item class by start of class. A boolean function that returns true only if a requested quantity of a particular time is Available A Purchase method that subtracts the number of times purchased from the number in stock and returns the total cost of purchasing the specified number of items A Restock method that adds the number of items that has been added to the inventory. A PriceChange method that enbles a change in price of an item after it has been created.

if this conditional is true control jumps to here Adding New Items to the Inventory while (true) { name = ""; Console.Write("Enter item name...................................... "); name = Console.ReadLine(); if (name == "") break; Console.Write("Enter initial number of items........................ "); quantity = Convert.ToInt32(Console.ReadLine()); Console.Write("Enter retail price................................... "); price = Convert.ToDouble(Console.ReadLine()); items.Add(new Item(name, quantity, price)); } if this conditional is true control jumps to here With the while(true) loop the user can add new items to the inventory list until an empty string is entered for an item name. If the string name is equal to the empty string then the break command causes the program to break out of the loop and jump to the first instruction beyond the loop. Notice: The while(true) loop is not a very elegant control structure. However, this one is simple and will do for now.

Writing a Text File to the Hard Drive We have learned how to read a text file using StreamReader...Now we look at how to write a text file using StreamWriter. Both of these are part of the System.IO collection of tools. StreamWriter tw = new StreamWriter("products.txt"); foreach(Item itm in items) { tw.WriteLine(itm.GetQuantity() + " " + itm.GetPrice() + " " + itm.GetName()); } tw.WriteLine("eof"); tw.Close(); It is very important that you close the file. This will ensure that any data left in the output buffer is written to the hard drive and the file is properly terminated with an end-of-file marker.