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.

Slides:



Advertisements
Similar presentations
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Advertisements

Introduction to Eclipse. Start Eclipse Click and then click Eclipse from the menu: Or open a shell and type eclipse after the prompt.
A3.1 Assignment 3 Simple Job Submission Using GT 4 GRAM.
Thread synchronization Example:Producer/Consumer Relationship Buffer –Shared memory region Producer thread –Calls produce method to add item to buffer.
1 Fall 2009ACS-1903 The break And continue Statements a break statement can be used to abnormally terminate a loop. use of the break statement in loops.
Introduction to the C# Programming Language for the VB Programmer.
1 Fall 2008ACS-1903 for Loop Reading files String conversions Random class.
Guide To UNIX Using Linux Third Edition
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.
Chapter 6: Iteration Part 2. Create triangle pattern [] [][] [][][] [][][][] Loop through rows for (int i = 1; i
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.
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.
Java - Classes JPatterson. What is a class? public class _Alpha { public static void main(String [] args) { } You have been using classes all year – you.
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.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
CS1101: Programming Methodology Preparing for Practical Exam (PE)
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.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. CSC 110 – INTRO TO COMPUTING - PROGRAMMING For Loop.
Programming in Java Transitioning from Alice. Becomes not myFirstMethod but …. public static void main (String[] arg) { // code for testing classes goes.
Lesson 11. CGI CGI is the interface between a Web page or browser and a Web server that is running a certain program/script. The CGI (Common Gateway Interface)
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
Debugging Dwight Deugo
Building Your Own Class
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
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
Module 4 Loops and Repetition 2/1/2019 CSE 1321 Module 4.
Structured Variables & File Systems
Debugging Dwight Deugo
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

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 Specifications for inventoryApp

Creating a new Console Application inventoryApp

Adding an Instance Class

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(); } A Test Program for inventoryApp

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; } inventoryApp Class without Accessors

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

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. 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 shapes = new List (); 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.

using System; using System.Collections.Generic; namespace inventoryApp { class Program { static void Main(string[] args) { List items = new List (); 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(); } 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. Later we will learn how to read and write text files using C#...(see example on next slide).

static void Main(string[] args) { string name; int quantity; double price; List items = new List (); 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(); } Reading from a Textfile Widget Geegaw Doodad eof products.txt This text file is placed in the Debug directory of the project along with the executable (.exe) program. Note: This is for future reference only. You are not being asked to create a program that reads a textfile at this time.

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.

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)); } Adding New Items to the Inventory 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. if this conditional is true control jumps to here

StreamWriter tw = new StreamWriter("products.txt"); foreach(Item itm in items) { tw.WriteLine(itm.GetQuantity() + " " + itm.GetPrice() + " " + itm.GetName()); } tw.WriteLine("eof"); tw.Close(); 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. 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.