Free Essay

Strings

In:

Submitted By lather10
Words 2908
Pages 12
MODERN PROGRAMMING TOOLS AND TECHNIQUES-1 String and StringBuffer

string
• Unlike many other languages that implement strings as character arrays, Java implements strings as objects of type String. • Advantage of creating strings as objects is that String objects can be constructed a number of ways, making it easy to obtain a string when needed.

• Once a String object has been created, you cannot change the characters that comprise that string.
• You can still perform all types of string operations. The difference is that each time we need an altered version of an existing string, a new String object is created that contains the modifications. The original string is left unchanged. • This approach is used because fixed, immutable strings can be implemented more efficiently than changeable ones.

string
• For those cases in which a modifiable string is desired, Java provides two options: StringBuffer and StringBuilder. Both hold strings that can be modified after they are created. • The String, StringBuffer, and StringBuilder classes are defined in java.lang. Thus, they are available to all programs automatically.
• The String, StringBuffer, and StringBuilder classes are declared final, which means that none of these classes may be subclassed.

The String Constructors
• The String class supports several constructors. To create an empty String, you call the default constructor. For example, String s = new String(); will create an instance of String with no characters in it.

• Frequently, we want to create strings that have initial values. The String class provides a variety of constructors to handle this. To create a String initialized by an array of characters, use the constructor shown here: String(char chars[ ]) Here is an example: char chars[] = { 'a', 'b', 'c' }; String s = new String(chars); This constructor initializes s with the string “abc”.

The String Constructors
• We can specify a subrange of a character array as an initializer using the following constructor: String(char chars[ ], int startIndex, int numChars) Here, startIndex specifies the index at which the subrange begins, and numChars specifies the number of characters to use. Here is an example: char chars[] = { 'a', 'b', 'c', 'd', 'e', 'f' }; String s = new String(chars, 2, 3);

The String Constructors
• We can construct a String object that contains the same character sequence as another String object using this constructor: String(String strObj) Here, strObj is a String object. Consider this example: // Construct one String from another. class MakeString { public static void main(String args[]) { char c[] = {'J', 'a', 'v', 'a'}; String s1 = new String(c); String s2 = new String(s1); System.out.println(s1); System.out.println(s2); } }

The String Constructors
• Because 8-bit ASCII strings are common, the String class provides constructors that initialize a string when given a byte array. Their forms are shown here:

String(byte asciiChars[ ]) String(byte asciiChars[ ], int startIndex, int numChars) Here, asciiChars specifies the array of bytes. The second form allows us to specify a subrange. In each of these constructors, the byte-to-character conversion is done by using the default character encoding of the platform. The following program illustrates these constructors: // Construct string from subset of char array. class SubStringCons { public static void main(String args[]) { byte ascii[] = {65, 66, 67, 68, 69, 70 }; String s1 = new String(ascii); System.out.println(s1); String s2 = new String(ascii, 2, 3); System.out.println(s2);

The String Constructors
• The contents of the array are copied whenever we create a String object from an array. If we modify the contents of the array after we have created the string, the String will be unchanged.

String Length
• The length of a string is the number of characters that it contains. To obtain this value, call the length( ) method, shown here: int length( ) • The following fragment prints “3”, since there are three characters in the string s: char chars[] = { 'a', 'b', 'c' }; String s = new String(chars); System.out.println(s.length());

String Literals
• The earlier examples showed how to explicitly create a String instance from an array of characters by using the new operator. However, there is an easier way to do this using a string literal. • For each string literal in your program, Java automatically constructs a String object. Thus, you can use a string literal to initialize a String object. For example, the following code fragment creates two equivalent strings: char chars[] = { 'a', 'b', 'c' }; String s1 = new String(chars); String s2 = "abc"; // use string literal It calls the length( ) method on the string “abc”. As expected, it prints “3”. System.out.println("abc".length());

String Concatenation with Other Data Types int age = 9; String s = "He is " + age + " years old."; System.out.println(s); String s = "four: " + 2 + 2; System.out.println(s);

Character Extraction charAt( )
To extract a single character from a String, you can refer directly to an individual character via the charAt( ) method. It has this general form: char charAt(int where) Here, where is the index of the character that you want to obtain. The value of here must be nonnegative and specify a location within the string. charAt( ) returns the character at the specified location. For example, char ch; ch = "abc".charAt(1); assigns the value “b” to ch.

Character Extraction getChars( ) If you need to extract more than one character at a time, you can use the getChars( ) method. It has this general form: void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)

class getCharsDemo { public static void main(String args[]) { String s = "This is a demo of the getChars method."; int start = 10; int end = 14; char buf[] = new char[end - start]; s.getChars(start, end, buf, 0); System.out.println(buf); } }

Character Extraction getBytes( ) getBytes( ) uses the default character-to-byte conversions provided by the platform. Here is its simplest form: byte[ ] getBytes( ) getBytes( ) is most useful when you are exporting a String value into an environment that does not support 16-bit Unicode characters. For example, most Internet protocols and text file formats use 8-bit ASCII for all text interchange. toCharArray( ) If you want to convert all the characters in a String object into a character array, the easiest way is to call toCharArray( ). It returns an array of characters for the entire string. Its general form is: char[ ] toCharArray( ) This function is provided as a convenience, since it is possible to use getChars( ) to achieve the same result.

Byte Extraction class TestingByteArrayCharArray { public static void main(String[] args) { String a=new String(); a="testing get bytes"; byte charArray[]=new byte[a.length()]; charArray=a.getBytes(); for(byte i: charArray) { System.out.println(i); } } }

class TestingByteArrayCharArray { public static void main(String[] args) { String a=new String(); a="testing get bytes"; byte byteArray[]=new byte[a.length()]; byteArray=a.getBytes(); for(byte i: byteArray) { System.out.println(i); } //System.out.println(a[5]); char charArray[]=new char[a.length()]; charArray=a.toCharArray(); for(int i=0; i 0) { String t = arr[j]; arr[j] = arr[i]; arr[i] = t; } } System.out.println(arr[i]); } } }

compareTo( )
• compareTo( ) takes into account uppercase and lowercase letters. The word “Now” came out before all the others because it begins with an uppercase letter, which means it has a lower value in the ASCII character set. • If we want to ignore case differences when comparing two strings, use compareToIgnoreCase( ), as shown here: int compareToIgnoreCase(String str)

Searching Strings
• The String class provides two methods that allow you to search a string for a specified character or substring: • indexOf( ) Searches for the first occurrence of a character or substring. • lastIndexOf( ) Searches for the last occurrence of a character or substring.

Searching Strings
• To search for the first occurrence of a character, use int indexOf(int ch) • To search for the last occurrence of a character, use int lastIndexOf(int ch) Here, ch is the character being sought. • To search for the first or last occurrence of a substring, use int indexOf(String str) int lastIndexOf(String str) Here, str specifies the substring. • You can specify a starting point for the search using these forms: int indexOf(int ch, int startIndex) int lastIndexOf(int ch, int startIndex) int indexOf(String str, int startIndex) int lastIndexOf(String str, int startIndex)

Searching Strings
// Demonstrate indexOf() and lastIndexOf(). class indexOfDemo { public static void main(String args[]) { String s = "Now is the time for all good men " + "to come to the aid of their country."; System.out.println(s); System.out.println("indexOf(t) = " +s.indexOf('t')); System.out.println("lastIndexOf(t) = " +s.lastIndexOf('t')); System.out.println("indexOf(the) = " +s.indexOf("the")); System.out.println("lastIndexOf(the) = " +s.lastIndexOf("the")); System.out.println("indexOf(t, 10) = " +s.indexOf('t', 10)); System.out.println("lastIndexOf(t, 60) = " +s.lastIndexOf('t', 60)); System.out.println("indexOf(the, 10) = " +s.indexOf("the", 10)); System.out.println("lastIndexOf(the, 60) = " + s.lastIndexOf("the", 60)); } }

Searching Strings indexOf(t) = 7 lastIndexOf(t) = 65 indexOf(the) = 7 lastIndexOf(the) = 55 indexOf(t, 10) = 11 lastIndexOf(t, 60) = 55 indexOf(the, 10) = 44 lastIndexOf(the, 60) = 55

Modifying a String
• Because String objects are immutable, whenever we want to modify a String, you must either copy it into a StringBuffer or StringBuilder, or use one of the following String methods, which will construct a new copy of the string with your modifications complete. • substring( )

• You can extract a substring using substring( ). It has two forms. The first is String substring(int startIndex). Here, startIndex specifies the index at which the substring will begin. This form returns a copy of the substring that begins at startIndex and runs to the end of the invoking string. • The second form of substring( ) allows us to specify both the beginning and ending index of the substring: String substring(int startIndex, int endIndex)
• Here, startIndex specifies the beginning index, and endIndex specifies the stopping point. The string returned contains all the characters from the beginning index, up to, but not including, the ending index.

Modifying a String
// Substring replacement. class StringReplace { public static void main(String args[]) { String org = "This is a test. This is, too."; String search = "is"; String sub = "was"; String result = ""; int i; do { // replace all matching substrings System.out.println(org); i = org.indexOf(search); if(i != -1) { result = org.substring(0, i); result = result + sub; result = result + org.substring(i + search.length()); org = result; } } while(i != -1); } }

concat
We can concatenate two strings using concat( ), shown here: String concat(String str) This method creates a new object that contains the invoking string with the contents of str appended to the end. concat( ) performs the same function as +. For example, String s1 = "one"; String s2 = s1.concat("two"); puts the string “onetwo” into s2. It generates the same result as the following sequence: String s1 = "one"; String s2 = s1 + "two";

replace( )
The replace( ) method has two forms. The first replaces all occurrences of one character in the invoking string with another character. It has the following general form: String replace(char original, char replacement)

Here, original specifies the character to be replaced by the character specified by replacement. The resulting string is returned. For example, String s = "Hello".replace('l', 'w'); puts the string “Hewwo” into s. The second form of replace( ) replaces one character sequence with another. It has this general form: String replace(CharSequence original, CharSequence replacement)

trim( )
The trim( ) method returns a copy of the invoking string from which any leading and trailing whitespace has been removed. It has this general form: String trim( ) Here is an example: String s = " Hello World ".trim(); This puts the string “Hello World” into s. The trim( ) method is quite useful when you process user commands.

Changing the Case of Characters Within a String
String toLowerCase( ) String toUpperCase( ) // Demonstrate toUpperCase() and toLowerCase(). class ChangeCase { public static void main(String args[]) { String s = "This is a test."; System.out.println("Original: " + s); String upper = s.toUpperCase(); String lower = s.toLowerCase(); System.out.println("Uppercase: " + upper); System.out.println("Lowercase: " + lower); } }

StringBuffer
• String represents fixed-length, immutable character sequences. • In contrast, StringBuffer represents growable and writeable character sequences. StringBuffer may have characters and substrings inserted in the middle or appended to the end.
• StringBuffer will automatically grow to make room for such additions and often has more characters pre-allocated than are actually needed, to allow room for growth.

StringBuffer Constructors
• StringBuffer defines these four constructors: StringBuffer( ) StringBuffer(int size) StringBuffer(String str) StringBuffer(CharSequence chars)
The default constructor (the one with no parameters) reserves room for 16 characters without reallocation. The second version accepts an integer argument that explicitly sets the size of the buffer.







The third version accepts a String argument that sets the initial contents of the StringBuffer object and reserves room for 16 more characters without reallocation.
The fourth constructor creates an object that contains the character sequence contained in chars.



length( ) and capacity( )
The current length of a StringBuffer can be found via the length( ) method, while the total allocated capacity can be found through the capacity( ) method. They have the following. general forms: int length( ) int capacity( )

// StringBuffer length vs. capacity. class StringBufferDemo { public static void main(String args[]) { StringBuffer sb = new StringBuffer("Hello"); System.out.println("buffer = " + sb); System.out.println("length = " + sb.length()); System.out.println("capacity = " + sb.capacity()); } }

ensureCapacity( )
• If we want to preallocate room for a certain number of characters after a StringBuffer has been constructed, you can use ensureCapacity( ) to set the size of the buffer. This is useful if you know in advance that you will be appending a large number of small strings to a StringBuffer.
• ensureCapacity( ) has this general form: void ensureCapacity(int capacity) Here, capacity specifies the size of the buffer.

setLength( )
• To set the length of the buffer within a StringBuffer object, use setLength( ). Its general form is: void setLength(int len) • len specifies the length of the buffer. This value must be nonnegative. • When we increase the size of the buffer, null characters are added to the end of the existing buffer. • If we call setLength( ) with a value less than the current value returned by length( ), then the characters stored beyond the new length will be lost.

charAt( ) and setCharAt( )
• The value of a single character can be obtained from a StringBuffer via the charAt( ) method. You can set the value of a character within a StringBuffer using setCharAt( ). Their general forms are shown here: char charAt(int where) void setCharAt(int where, char ch)
// Demonstrate charAt() and setCharAt(). class setCharAtDemo { public static void main(String args[]) { StringBuffer sb = new StringBuffer("Hello"); System.out.println("buffer before = " + sb); System.out.println("charAt(1) before = " + sb.charAt(1)); sb.setCharAt(1, 'i'); sb.setLength(2); System.out.println("buffer after = " + sb); System.out.println("charAt(1) after = " + sb.charAt(1)); } }

getChars( )
• To copy a substring of a StringBuffer into an array, use the getChars( ) method. It has this general form: void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)

append( )




The append( ) method concatenates the string representation of any other type of data to the end of the invoking StringBuffer object. It has several overloaded versions. Here are a few of its forms:

StringBuffer append(String str) StringBuffer append(int num) StringBuffer append(Object obj) • String.valueOf( ) is called for each parameter to obtain its string representation. The result is appended to the current StringBuffer object. // Demonstrate append(). class appendDemo { public static void main(String args[]) { String s; int a = 42; StringBuffer sb = new StringBuffer(40); s = sb.append("a = ").append(a).append("!").toString(); System.out.println(s); } }

insert( )
The insert( ) method inserts one string into another. It is overloaded to accept values of all the simple types, plus Strings, Objects, and CharSequences. It calls String.valueOf( ) to obtain the string representation of the value it is called with. This string is then inserted into the invoking StringBuffer object. These are a few of its forms: StringBuffer insert(int index, String str) StringBuffer insert(int index, char ch) StringBuffer insert(int index, Object obj) class insertDemo { public static void main(String args[]) { StringBuffer sb = new StringBuffer("I Java!"); sb.insert(2, "like "); System.out.println(sb); } }

reverse( )
// Using reverse() to reverse a StringBuffer. class ReverseDemo { public static void main(String args[]) { StringBuffer s = new StringBuffer("abcdef"); System.out.println(s); s.reverse(); System.out.println(s); } }

delete( ) and deleteCharAt( )
• StringBuffer delete(int startIndex, int endIndex) • StringBuffer deleteCharAt(int loc) class deleteDemo { public static void main(String args[]) { StringBuffer sb = new StringBuffer("This is a test."); sb.delete(4, 7); System.out.println("After delete: " + sb); sb.deleteCharAt(0); System.out.println("After deleteCharAt: " + sb); } }

replace( )
• We can replace one set of characters with another set inside a StringBuffer object by calling replace( ). Its signature is shown here:
StringBuffer replace(int startIndex, int endIndex, String str) • The substring being replaced is specified by the indexes startIndex and endIndex. Thus, the substring at startIndex through endIndex–1 is replaced. The replacement string is passed in str. • The resulting StringBuffer object is returned. // Demonstrate replace() class replaceDemo { public static void main(String args[]) { StringBuffer sb = new StringBuffer("This is a test."); sb.replace(5, 7, "was"); System.out.println("After replace: " + sb); } }

substring( )
• substring( ) has the following two forms:
String substring(int startIndex) String substring(int startIndex, int endIndex)

indexOf( ) and lastIndexOf( ) class IndexOfDemo { public static void main(String args[]) { StringBuffer sb = new StringBuffer("one two one"); int i; i = sb.indexOf("one"); System.out.println("First index: " + i); i = sb.lastIndexOf("one"); System.out.println("Last index: " + i); } }

Similar Documents

Free Essay

String Theory

...Craig Kalucki Comparitive Religion Tues 4-6:50 String theory and Universal Theories If we can take a looks garment from a sweater, and pull one string such as in a cartoon, the sweater will untangle leaving a pile of string on the floor. Basically what this implies is we break down something in its simplest form, and all we have left are tiny bits of string, which is basically similar to “String Theory”. string theory uses a model of one-dimensional strings in place of the particles of quantum physics. These strings, the size of the Planck length vibrate at specific resonant frequencies. The formulas that result from string theory predict more than four dimensions but the extra dimensions are "curled up" within the Planck length. In addition to the strings, string theory contains another type of fundamental object called a brane, which can have many more dimensions. In some "braneworld scenarios," our universe is actually "stuck" inside of a 3-dimensional brane, called a 3-brane. Common Sense tells us we live in a world defined by three spatial dimensions and one dimension of time. Mainly, it only takes three numbers to pinpoint your physical location at any given moment. On Earth, these coordinates break down to longitude, latitude and altitude representing the dimensions of length, width and height (or depth). If we put a time stamp on those coordinates, we are pinpointed in time as well. To strip that down even more, a one-dimensional world would be like...

Words: 1051 - Pages: 5

Free Essay

Sweet Sounding Strings: Changing Guitar Strings Made Easy

...Take a look at your guitar strings. Are they in good shape? Are they silver and shiny? Are six strings there? If it's been several months since you put new strings on your guitar, or if you answered no to any of these questions, it’s time for a string change. Guitar strings on the guitar are just like knees on a baby’s jeans: they wear out easy, and should become a regular part of your guitar care routine. Even the oils in your fingers deteriorate the string. Some people fret over the techniques of replacing their own guitar strings. String changes can be stress-free; it takes little practice, should take only a few minutes per string, and will provide a bright, clear sound from your guitar. Anyone who knows how to play the guitar should know how to perform their own string changes on a basic electric guitar. Many music stores offer restringing for a fee, which can add up quickly if you have a number of guitars to maintain. And the need for a string change can happen at any time, not just when it is convenient to run to a store to have them do it for you. To begin, collect all of the tools you will need. These include a wire cutter or pair of pliers capable of cutting wire, a thick bath towel to protect your instrument’s finish while on your working surface, and a new set of strings. You will need a tuner for when you have your strings on, so you can tune them. To remove fingerprints and oils from the fret board and off of the finished areas, you will want to use...

Words: 1172 - Pages: 5

Free Essay

Java Programming

...Value EV Integer End Value Output Variable NOS Integer Numbers OD Integer Odd numbers EV Integer Even numbers III. Output Layout IV. Codes import java.util.Scanner; public class EvenOdd { public static void main (String[]args) { int a; int b; Scanner in = new Scanner (System.in); System.out.print ("Starting Value: "); a=in.nextInt(); System.out.print ("End Value: "); b=in.nextInt(); System.out.println("number\t"+"odd\t"+"even\t"); for(int i=a; i<=b;i++) { System.out.print(i); if(i%2==0) { System.out.println("\t\t"+i );//even } else { System.out.println("\t"+i); //odd } } } } Activity 2: Transaction I. Problem Create an application that will transact the following item codes with looping and will print a receipt. II. Analysis Input Variable Data Type Description A Integer Letter A Price B Integer Letter B Price C Integer Letter C Price D Integer Letter D Price E Integer Letter E Price q Integer Quantity tno Integer Transaction Number ic String Item Code ap Integer Amount Paid Output Variable ipriceA Integer Total Amount in A ipriceB Integer Total Amount in B ipriceC Integer Total Amount in C ipriceD Integer Total Amount in D ipriceE Integer Total Amount in E 3 vat Integer 12%...

Words: 1321 - Pages: 6

Free Essay

C Programming

...C PROGRAMMING Section 1. Topics: Functions Statements Input Output Variables Introduction The C programming language has been the most popular high level language used for engineering applications for the last 20 years. It shares many common structures with other procedural languages, such as Pascal, and can be used for general purpose programming of a PC. However, it is also particularly good for development of embedded application programs such as those found in phones, video recorders and so forth. The term procedural language refers to the fact that the language uses procedures to do particular tasks such as printing on the screen. In C these procedures are known as functions and are described below. What is so good about a language like C? The basic reason such languages were developed was to make it easier for humans to program computers. The alternative is the language of the computer, i.e., binary codes. Clearly such ‘low-level’ languages are not very appealing for humans, although sometimes necessary for detailed engineering work. (In fact C is often ‘mixed’ with such languages for engineering applications.) C uses words and symbols that are part of, or similar to, normal language. This makes it easier for programmers to develop code. The C code is converted to the machine code by a special program called a compiler. See note 1. But perhaps the most useful thing about such a language is that it provides the developer with a library of ‘mini-programs’...

Words: 3795 - Pages: 16

Free Essay

Bacon

...the variable 2. Specify a legitimate and unique name for the variable. Naming rules for variables: 1. Must start with a letter or underscore( _ ) 2. Second and subsequent characters can be alpha numeric 3. Do not use any special characters or punctuation marks including space 4. Do not use any key words or reserved words for naming variables; Ex: String, integer, me, if, loop, else- you will see the key words in blue color. 5. Choose a name that reflects the content for the variable Examples: 1) A1 as the variable name: valid but does not reflect the content 2) 3TestScores - Not valid because it starts with a number midTermTestScore - camel casing convention is followed to name the variables. Capitalize the first letter of second and subsequent words in the variable's name. This is not syntax and the compiler does not give an error if camel casing is not followed. This is for our own reading and documentation purposes. Data types: 1. Numeric a. Integer Ex: 2, 5, -10, -21, 0 b. Decimal Ex: 1.56, 8.456,-3.2 2. Text a. Single letter - Character b. Multi letter - String 3. Alphanumeric – String 4. Boolean – True or false Visual logic is case sensitive: testScore, TESTSCORE, TeStScOre, testscore refer to different variables. Variable declaration: 1.integer testScore This statement declares testScore variable as of Integer data type. It assigns 0 to testScore...

Words: 469 - Pages: 2

Free Essay

Visual Basic

...Visual Basic – Messages and data input/output Introduction One way for a user to communicate with a procedure is via a dialogue box. The easiest way to do this in VB is to use one of the pre-defined ones. VB has two kinds, a Message box and an Input box. Message box The MsgBox function displays a message, waits for the user to click a button and returns a value indicating which button has been chosen. The simplest MsgBox contains only a message string and an OK button. The general syntax is MsgBox(prompt [,buttons] [,title]), where the quantities within [] are optional arguments, with prompt: string expression displayed in the message (max length 1024 characters) buttons: numerical expression that is sum of values specifying the type of buttons to display, title: string expression displayed in the title bar. Some of the button values are given below. (For a full list see the Help file). Value Constant Display 0 vbOKOnly OK button only 1 vbOKCancel OK and Cancel buttons 3 vbYesNoCancel Yes, No and Cancel buttons 4 vbYesNo Yes and No buttons 32 vbQuestion Query icon 48 vbExclamation Warning message icon 0 vbDefaultButton1 First button is default 256 vbDefaultButton2 Second button is default 512 vbDefaultButton3 Third button is default The value returned by the MsgBox function depends on the button pressed. Some values are listed below. Button selected Value Constant OK 1 vbOK Cancel 2 vbCancel Yes 6 vbYes No 7 vbNo The MsgBox function can be used as a simple debug tool. To...

Words: 930 - Pages: 4

Free Essay

Computer Science

...another . These type of conversion is called Explicit conversion . An explicit conversion uses a type conversion keyword. With these conversion keywords we have to perform the Explicit Conversion. String.Format(), creates strings by combining string values with other data types and controlling how each value is displayed. Rather than formatting values individually and then concatenating them, Format() works with a string that specifies insertion points in its text. These insertion points are then replaced with the actual values. Being a string itself, the format string can be loaded from external files and resources, allowing for flexible string handling that can be convenient when working with internationalized and localized applications. Format specifiers are special symbols that specify the way data is formatted during its conversion to a string. This topic describes frequently used standard and custom format specifiers used to format numeric and date/time values.  Table A-1 Variables Prefixes Prefix | Data Type | byt | Byte | b | Boolean | cur | Currency | d | Double | dte | Date | f | Single | hf | File handle (Long) | hwnd | Window handle (Long) | h(... lowercase) | Handle to something (Long) | l | Long | n | Integer | o | Object | s | String | v | Variant | Table A-2 Modifiers and Special Types Prefixes Prefix | Data Type | a | Array <of another type> | C | Class or class instance | t |...

Words: 728 - Pages: 3

Free Essay

Semantics of Visual Basics

...| Purpose In this project, a database management system will be implemented to make the self-ordering easier. The users for this program will be used for customers in various restaurants. It will take a customer’s order, total it, and give them an amount. The system will instruct the customer to enter the correct amount. If the amount is not enough, the system will instruct them to enter more money. If it is too less, however, the system will them issue out change. Use of Visual Basics Visual Basic for Applications (VBA) will be used because it is a programming language built right into many Microsoft programs. This language is built on the Basic programming language made popular by PCs over the past 25 years. VBA shares similarities with other Windows implementations of the Basic language, such as Visual Basic. If you are familiar with programming in a different language (including using macros), you can quickly get up to speed with VBA. There are a few terms you should know before you start programming in VBA: * Procedure. A section of programming code, designed to accomplish a specific task, which your program statements can use throughout your program. There are two types of procedures: functions and subroutines. * Function. A procedure that returns a value after it completes its task. When called, functions typically appear on the right side of an equal sign in an expression. * Subroutine. A procedure that does not return a value after it completes its...

Words: 3627 - Pages: 15

Free Essay

Cis115

...terms of pseudocode or program notes, input-process-output (IPO) analysis, and flow chart. * TCO 7: Given a program with logic errors that is intended as a solution to a simple problem, employ debugging diagnostics to remove and correct the errors. TCO 8: Given a more complex problem, develop a complete solution that includes a comprehensive statement of the problem, complete program design, and program documentation. Scenario Your algorithm will write two functions called ComputeTotal( ) and ComputeTax( ). ComputeTotal( ) will receive the quantity of items purchased, and the unit price of each item. It will return the total sales (quantity times price). ComputeTax( ) will receive total sales as a number and the state as a string and return the amount of tax depending on the state. NJ requires 7% tax, FL requires 6% tax, and NY has 4% tax. The main program will ask for the name of the customer and read the name in a variable called name. It will also ask for one of the three states listed above. It will ask for the number of items sold and the unit price of the item. Main will then call ComputeTotal( ), passing the quantity and unit price. Main will then call ComputeTax( ), passing the state and the amount of sales and receive back the tax. Finally Main( ) will print out the total sales, the tax amount, and the total with taxes. For example, see below. Enter the name of the customer: Jack In which state (NY / NJ / FL) ? NJ How many items were purchased...

Words: 784 - Pages: 4

Free Essay

Strings - Java

...(Displaying Strings in Uppercase and Lowercase) Write a program that inputs a line of text into char array s[100]. Output the line in uppercase letters and in lowercase letters. Enter a line of text: A line with UPPER- and lowercase LeTters The line in uppercase is: A LINE WITH UPPER- AND LOWERCASE LETTERS The line in lowercase is: a line with upper- and lowercase letters (Converting Strings to Integers for Calculations) Write a program that inputs four strings that represent integers, converts the strings to integers, sums the values and prints the total of the four values. Enter an integer string: 43 Enter an integer string: 77 Enter an integer string: 120 Enter an integer string: 9999 The total of the values is 10239 (Random Sentences) Write a program that uses random number generation to create sentences. The program should use four arrays of pointers to char called article, noun, verb and preposition. The program should create a sentence by selecting a word at random from each array in the following order: article, noun, verb, preposition, article and noun. As each word is picked, it should be concatenated to the previous words in an array large enough to hold the entire sentence. The words should be separated by spaces. When the final sentence is output, it should start with a capital letter and end with a period. The program should generate 20 such sentences. The arrays should be filled as follows: The article array should contain the...

Words: 1497 - Pages: 6

Free Essay

Ieee 1450 Stil Bnf

...For a complete definition of STIL please refer to the P1450 document. Please remember this BNF is considered an incomplete representation of the language. 1.0 STIL Organization stil_session ::= stil [header] session session ::= block | session block block ::= user_keywords | user_functions | signals | signal_groups | pattern_exec | pattern_burst | timing | spec | selector | scan_structs | pattern | procedures | macro_defs | include | annotation | udb | (null) 2.0 STIL Statement stil ::= STIL stil_version_number ";" stil_version_number ::= integer "." integer 3.0 Header Block header ::= Header "{" [header_list] "}" header_list ::= header_item | header_list header_item header_item ::= Title string ";" | Date date_string ";" | Source string ";" | History "{" [ history_list ]"}" | include |...

Words: 1480 - Pages: 6

Premium Essay

Homework

...If modules use global variables it is dependent upon the module and if other modules are presented you have to redesign all over each time. 4.It makes a program hard to understand since it can be modified and have to be aware of all other parts of the program that access it. 5.Global variables are not writing direct into flowcharts. 2. How can you declare global and local variables in flowcharts? Global variables are displayed in pseudocode but not in flowcharts directly. 3. How can you declare global and local variables in pseudocode? You can declare variables using the Global, Local, or Component statements, or you can use local variables without declaring them. Here are some examples: Local Number &AGE; Global String &OPER_NICKNAME; Component Rowset &MY_ROWSET; Local Any &SOME_FIELD; Local ApiObject &MYTREE; Local Boolean &Compare = True; Variable declarations are usually placed above the main body of a PeopleCode program (along with function declarations and definitions). The exception is the Local declaration, which you can use within a function or the main section of a program. You can declare variables as any of the PeopleCode data types. If a variable is declared as an Any data type, or if a variable is not declared, PeopleTools uses...

Words: 314 - Pages: 2

Premium Essay

Student

...COMP101 – Problem Solving with Computing Homework - WEEK 2 [30 points] This is a review of some of the material from Chapter 2 and lectures from class. No credit for answers that are copies or near verbatim transcripts – please use your own words1 and document sources where appropriate. 1 This will apply to all assignments in this class. Answer the following questions: Chapter 2 1. Short Answers [1 point each, 2 points total] 1. What does a professional programmer usually do first to gain an understanding of a problem? The first thing that a professional programmer usually do first to gain an understanding of a program is to closely relate customer (Interview ) to inquire or gather information about the problem. 2. What two things must you normally specify in a variable declaration? The two things normally specified in a variable declaration are the variable type and identifier. 2. Algorithms / Pseudocode [1 point each, 5 points total] 1. Design an algorithm that prompts the user to enter his or her height and stores the user’s input in a variable named height. Declare height Display “Enter Your Height” Input Height Display “Height” 2. Write assignment statements that perform the following operations with the variables a and b. - Adds 2 to a and stores the result in b. - Subtracts 8 from b and stores the result in a Set b=2+a Set a=b-8 3. Write a pseudocode statement that declares the variable cost so it can hold real numbers. Floating...

Words: 1823 - Pages: 8

Premium Essay

A Piece of String

...LaTasha Smith 16 August 2012 A Piece of String The short story of A Piece of String was written by Guy de Maupassant in 1883. It is a short story based on in my opinion the theory of “guilty until proven innocent”. The moral of the story is that you must tell the truth to maintain a reputation of honesty and gain trust from others, because a reputation of deceit and dishonesty will make people believe you are not trustworthy, so even when you're telling the truth, it is hard for others to believe. The main characters in The Piece of Strings are Maître Hauchecorne, M. Malandain and The Mayor of Goderville. Maître is a peasant, who picks up anything he sees as useful off the ground. The story begins where he is walking through the market and comes across a piece of string. He picks the string up and keeps it for himself. Later, in the Market, Maître Hanchecornes enemy accuses him of stealing someone else's pocketbook. This soon gets around Goderville, and people begin to distrust and dislike Maître Hauchecorne, despite his claim of innocence. Maître Hauchecorne already had a bad reputation with the citizens of Goderville due to his previous lying and over exaggerations and telling unbelievable stories. This is the main reason for the people's reluctance to believe Maître Hauchecorne, although he is telling the truth. The pocketbook is eventually returned, however the town still doesn’t believe his innocence. The pain and heartache that Maitre Hauchecorne suffered...

Words: 270 - Pages: 2

Free Essay

Java Programming

...A Programmer’s Guide to Java™ SCJP Certification Third Edition This page intentionally left blank A Programmer’s Guide to Java™ SCJP Certification A Comprehensive Primer Third Edition Khalid A. Mughal Rolf W. Rasmussen Upper Saddle River, New Jersey • Boston • Indianapolis • San Francisco New York • Toronto • Montreal • London • Munich • Paris • Madrid Capetown • Sidney • Tokyo • Singapore • Mexico City Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and the publisher was aware of a trademark claim, the designations have been printed with initial capital letters or in all capitals. The authors and publisher have taken care in the preparation of this book, but make no expressed or implied warranty of any kind and assume no responsibility for errors or omissions. No liability is assumed for incidental or consequential damages in connection with or arising out of the use of the information or programs contained herein. The publisher offers excellent discounts on this book when ordered in quantity for bulk purchases or special sales, which may include electronic versions and/or custom covers and content particular to your business, training goals, marketing focus, and branding interests. For more information, please contact: U.S. Corporate and Government Sales (800) 382-3419 corpsales@pearsontechgroup.com For sales outside the United...

Words: 15086 - Pages: 61