Chapter 2: The Basics of C++ Programming



Intro. to Java Programming

for Adv. Programmers

Hats I will wear this semester

|You |Me |

|[pic] |[pic] |

The SEVEN sections of a program

|Introduction/Name of Program |

|Import statements/Preprocessor commands |

|class header |

|class variables |

|Functions |

|main( ) |

|class closer |

|Part 1: Introduction/Name of Program |

| |

|Your name, class, and program name and a brief description of the program |

|Example: //Ryan Dorrill |

|//C++ AB |

|//Blackjack |

|Part 2: Import statements/Preprocessor commands |

| |

|Commands that include other library files, those files contain commands, functions, etc… |

| |

|import javac.swing.* // common library to include |

|Part 3: Class Header |

| |

|public class Hello // MUST SAVE FILE AS “Hello.java” |

|{ // classname and filename must match EXACTLY |

|… |

|Part 4: Class variables |

|Variables and values that can be accessed by any part of the CLASS. |

|Part 5: Functions |

|functions/procedures that help the MAIN program run. |

|Main calls these functions created here. |

|Part 6: Main program |

|The center of your program, where you call functions and display menus. |

|Example: |

|public static void main(String args[]) |

|{ …… // WHERE EVERYTHING BEGINS AND ENDS!!! |

|Part 7: Class closer |

|} // closing bracket to contain all code in class |

Input and Output

I/O stream

sc.nextDouble( ) System.out.println( )

sc.nextInt( ) System.out.print( )

Printing a Line of Text

|Print Example |

|// Mr. Lupoli |

|// 1st program |

| |

|public class Hello |

|{ |

|public static void main(String args[]) |

|{ |

|System.out.print("Hello Class, “); |

|System.out.println("I am Mr. Lupoli"); // what is the difference between |

|System.out.println("We will learn JAVA!!"); // println and print?? |

|} |

|} |

Use the code above to display YOUR name on line ONE, and your town and state on line TWO

Using System.out.println( ) with variables

int x = 0; // MUST DECLARE ALL VARIABLE BEFORE USING

int y = 8;

System.out.println(“X is: “ + x + “ and Y is: “ + y );

Introduction to the Scanner Class

Thanks to Mike McCoy and Jordan Clark

How to gather INPUT from the keyboard

The scanner class is a STANDARDIZED class that uses different methods for READING in values from either the KEYBOARD or a FILE.

Before this addition, many java programmers created their own scanner class to accomplish the same task

Remember

1 Keyboard ( System.in

|The Scanner’s Purpose and Creation |

|System.in (Keyboard) |

|Scanner sc = new Scanner(System.in); |

| |

|int score = sc.nextInt();... |

Scanner Important Information

Must import

1 java.util.Scanner;

Scanner will ignore white spaces BEFORE a value, but BY DEFAULT will STOP:

1 At a white space (those not reading in a line)

2 At a ‘\n’ (those reading in a line)

literal escape constants/command constants

|JAVA Escape Sequences |

|Escape Sequence |Description |

|\t |tab |

|\r |carriage return, go to beg. of next line |

|\\ |backslash |

|\” |double quote |

|\’ |single quote |

|\n |new line |

|\b |back space |

|\f |form feed |

What will these statements below display??

System.out.println(“Hi Class!”);

System.out.println(“Good Luck!!! \n”);

System.out.println(“\t \t You’ll need it!!!”);

Reading APIs

• “returning”

• Breakdown of methods

• Etc…

Methods in Scanner class

Just remember to first

2 INDENTIFY what exactly you wish to read in

3 HOW you want to use it.

Remember a numeric value CAN be read in as a String!!

Methods in the class are broken down into two categories

1 next() (reads value)

2 hasNext() (checks that a value is present to read)

| String |next() |

| |          Finds and returns the next complete token from this scanner. |

|// to read in a SINGLE char |

| |

|char letter; |

|letter = sc.next().charAt(0); |

| String |next(Pattern pattern) |

| |          Returns the next token if it matches the specified pattern. |

| String |next(String pattern) |

| |          Returns the next token if it matches the pattern constructed from the specified string. |

| BigDecimal |nextBigDecimal() |

| |          Scans the next token of the input as a BigDecimal. |

| BigInteger |nextBigInteger() |

| |          Scans the next token of the input as a BigInteger. |

| BigInteger |nextBigInteger(int radix) |

| |          Scans the next token of the input as a BigInteger. |

| boolean |nextBoolean() |

| |          Scans the next token of the input into a boolean value and returns that value. |

| byte |nextByte() |

| |          Scans the next token of the input as a byte. |

| byte |nextByte(int radix) |

| |          Scans the next token of the input as a byte. |

| double |nextDouble() |

| |          Scans the next token of the input as a double. |

| float |nextFloat() |

| |          Scans the next token of the input as a float. |

| int |nextInt() |

| |          Scans the next token of the input as an int. |

|int score = sc.nextInt(); OR int score; |

|score = sc.nextInt(); |

| int |nextInt(int radix) |

| |          Scans the next token of the input as an int. |

| String |nextLine() |

| |          Advances this scanner past the current line and returns the input that was skipped. |

| long |nextLong() |

| |          Scans the next token of the input as a long. |

| long |nextLong(int radix) |

| |          Scans the next token of the input as a long. |

| short |nextShort() |

| |          Scans the next token of the input as a short. |

| short |nextShort(int radix) |

| |          Scans the next token of the input as a short. |

Please note that there are MATCHING “hasNext” for each shown on the ditto.

Input/Output Homework Exercise

String name, address; // declare ALL variables before you use them

// string is used for STRING text

Scanner sc = new Scanner(System.in);

YOU DO NOT NEED TO CODE ANY IMPORTS, MAIN, ETC...

Just code the input/output lines of code.

1. ) Create the CODE to LITERALLY display YOUR name, and address (No variables yet.)

2.) Create the CODE to ask for user’s name and address, USE THE VARIABLES DECLARED FOR YOU ALREADY!! Hint: Which scanner functions will you need?

3. Create the code to display their name and address that THEY type in. NOT yours!!

Use of Comments

• same as C++

Arrays

0 1 2 3 4 5 6 7 8 9 10 11 …

x …

array name element index

NOTICE:

max_index + 1 = size

index starts at 0 not 1!!

Holds ONLY ONE value per element!!

Homogeneous -- all of the elements have to be of the same type, e.g., int, float, char, etc.

Declaration using different datatypes

• arrays need a NAME and a size

o name

▪ one word, CAMELCASE

▪ sodaPrice

▪ soda_Price

o size

▪ greater than 0

▪ extra is fine, but not too much!!!

• arrays will have a value in EACH ELEMENT automatically!!!

o used before in Computer

o called garbage!!!

o good to set value (below) to your choice of a default

type [] arrayname = new type[size];

|Declaration of Multiple datatype arrays |

|Double |double [] sodaPrice = new double[3]; |

| | |

| |[0] [1] [2] |

| |sodaPrice |

|Integer |int [] seasonPts = new int[13]; |

|String |String [] names = new String[25]; |

|Char |char [] alphabet = new char[26]; |

| |Draw what the “alphabet” array would look like |

Placing/Updating values in an element

• AFTER YOU HAVE DELCARED THE ARRAY!!!

• Slightly different syntax depending on data type

• notice DATATYPE is NOT placed in from of assignment

• YOU CAN CHANGE A VALUE AFTERWARD!! AT ANY TIME!!!

arrayname[index] = value;

|Placing values in multiple datatype arrays |

|Double |Integer |String |Char |

|//… declared here!!! |//… declared here!!! |//… declared here!!! |//… declared here!!! |

| | | |// … |

|double sodaPrice[0] = .65; | |names[0]= “Lupoli”; | |

|// incorrect code |seasonPts[0] = 13; |names[1]= “Akman”; |alphabet[0] = ‘A’; |

| |seasonPts[1] = 14; |names[2]= “Jensen”; |alphabet[1] = ‘B’; |

|sodaPrice[0] = .65; |seasonPts[2] = 8; |names[3]= “Harman”; |alphabet[2] = ‘C’; |

|sodaPrice[1] = .85; |seasonPts[3] = 25; |names[4]= “Martino”; |… |

|sodaPrice[2] = .75; |seasonPts[4] = 3; |names[5]= “Reardon”; |alphabet[25] = ‘Z’; |

| |… |… | |

| |seasonPts[12] = 26; |names[24]= “Myers”; | |

| | | | |

| | |names[1] = “Munson”; | |

In the alphabet array, why do we stop at 25?? (Other than last letter)

I made a mistake in seasonPts, the 3rd game should be 18, how do I fix it?

Displaying an element in an array (the long way)

• Display by each and every individual element

o THERE IS NO WAY TO DISPLAY THE ENTIRE ARRAY IN ONE LINE!!!

o System.out.print(sodaPrice + “\n”); // that will not display the entire array

• Display code is the SAME for all datatypes

o notice I use println() to print each ELEMENT on a separate line

|Displaying values in multiple datatype arrays |

|Double |Integer |String |Char |

|//… | |String [] names = new String[25]; |// … |

| |same as ( |// … | |

|System.out.println(sodaPrice[0]); | | |System.out.println(alphabet[0]); |

|System.out.println(sodaPrice[1]); | |System.out.println(names[0]); |System.out.println(alphabet[1]); |

|System.out.println(sodaPrice[2]); | |System.out.println(names[1]); |System.out.println(alphabet[2]); |

| | |System.out.println(names[2]); |… |

| | |System.out.println(names[3]); |System.out.println(alphabet[26]); |

| | |System.out.println(names[4]); | |

| | |… | |

| | |System.out.println(names[24]); | |

How many PrintLn statements would we need to display THE ENTIRE array of 150 elements??

Why MUST we place values in the array before we display them?

Using Repetition to display arrays

int [] x = new int[10];

// values filled in here

To display our simple “x” array, we would have to display each line separately:

System.out.println(x[0]);

System.out.println(x[1]);

System.out.println(x[2]);

System.out.println(x[3]);

System.out.println(x[4]);



Using Repetition to display arrays

• To display our simple “x” array, we would have to display each line separately:

• remember values have to be placed first before displaying!!!

|Displaying values into arrays using Loops |

|Non-loop |Loop |

| | |

|int test = new int[10]; // 10 test scores |int test = new int[10]; // 10 test scores |

| | |

|// after values are placed |// after values are placed |

| | |

|System.out.println(test[0]); |for(int i = 0; i < test.length; i++) |

|System.out.println(test[1]); |{ |

|System.out.println(test[2]); |System.out.println(test[i]); |

|System.out.println(test[3]); |} |

|System.out.println(test[4]); | |

|System.out.println(test[5]); | |

|… | |

|System.out.println(test[9]); | |

The length function

• “returns” the exact length (integer) of the array

• when creating arrays, there are features that come with it

• nice feature since you don’t have to remember!!! The computer will find out!!

• syntax

o array_name.length()

|Examples of length in use |

|Double |int size = sodaPrice.length; |

| | |

| |What will size be? |

|Integer |for(int i = 0; i < seasonPts.length; i++) |

| | |

| |What will seasonPts.length be? |

|String |System.out.println(“Size of array: “ + names.length); |

|Char |if(alphabet.length < 0) |

1. Create the loop to display the seasonPts values (Slip)

2. Create the loop to display the names values (Slip)

3. Now create a for loop to display the array “d” as such: (SLIP)

int [] d = new int [30];

d[0] = 11;

d[1] = 12;

d[2] = 13;

d[3] = 14;

d[4] = 15;

d[5] = 16;

d[6] = 17;

d[7] = 18;

d[8] = 19;

d[9] = 20;

… // to d[29]

|11|12|13|14|15|… | Yes, all on ONE line, yes | at the front and | at the end.

String Declaration and Initialization

• Sets aside an array of elements

o each element contains a String (single letter)

• Assigning values

o Must use “ “’s to set if literal

o variable = sc.next(); only reads up to the first white space.

o variable = sc.nextLine(); reads the whole line typed.

• don’t have to worry about declaring a SIZE that fits!! (automatically done!!)

• can use = to set a String

• can use + to concatenate

• No special treatment, just like any other variable

• MUST GIVE A DEFAULT VALUE!!! (“”)

String Declaration and Initialization

|Gathering values into Strings Example 1 |

|String firstName = “”, lastName = “”; |

|firstName = sc.next (); // input: Mr. Lupoli |

|lastName = sc.next (); |

|System.out.print(lastName + “, “ + firstName); // output: Lupoli, Mr. |

| |

|firstName |

|lastName |

| |

|M |

|r |

|. |

| |

| |

|L |

|u |

|p |

|o |

|l |

|i |

| |

| |

| |

|Gathering values into Strings Example 2 |

|String firstName = “Kristen”; |

|String lastName = “Davis”; |

|System.out.print(lastName + “, “ + firstName); // output: Davis, Kristen |

| |

|firstName |

|lastName |

| |

|K |

|r |

|i |

|s |

|t |

|e |

|n |

| |

| |

|D |

|a |

|v |

|i |

|s |

| |

| |

| |

|Gathering values into Strings Example 3 |

|String wholeName = “”; |

|wholeName = sc.nextLine(); // input: Mr. Lupoli |

|System.out.print(wholeName); // output: Lupoli, Mr. |

| |

|wholename |

|M |

|r |

|. |

| |

|L |

|u |

|p |

|o |

|l |

|i |

| |

| |

String methods in general

• there will be SO many applications where you will be working with strings

• knowing that they are arrays helps you understand what the methods below are doing and WHEN to use them

• “return”

o means method gives a value of a certain datatype back

Comparing Strings

• normal comparison symbols do not work!!

o == , =, !=, >, 0 no match, S1 is alphabetically greater than S2

• equals (boolean)

o answer if an EXACT match

• compareToIgnoreCase/equalsIgnoreCase

o ignore case of strings, works the same way

|compareTo |

| |

|// compareTo example |

|String testOne = "Lupoli"; |

|String testTwo = "Martino"; |

| |

|if(pareTo(testTwo) < 0) |

|{ System.out.println("testOne is LESS than testTwo"); } |

|else if(pareTo(testTwo) > 0) |

|{ System.out.println("testOne is GREATER than testTwo"); } |

|else // (pareTo(testTwo) == 0) |

|{ System.out.println("testOne is EQUAL to testTwo");} |

| |

|if(pareTo("Lupoli") == 0) |

|{ System.out.print("Strings matched"); } |

|equal |

| |

|// equal example |

|testOne = "Lupoli"; |

|testTwo = "Martino"; |

| |

|if(testOne.equals(testTwo)) |

|{ System.out.println("testOne is LESS than testTwo"); } |

|else // (testOne.equals(testTwo) == 0) |

|{ System.out.println("testOne is EQUAL than testTwo"); } |

| |

|if(testOne.equals("Lupoli")) |

|{ System.out.println("Strings matched"); } |

Editing elements in a String array

• HAVE TO DELCARE THE STRING FIRST!!!

• individual characters inside a String array can be accessed.

|Accessing a value inside an String |

|String fname = “John”; |

|System.out.print(“Character at index 2 is “ + fname[2] + “\n”); // displays ‘h’ |

| |

|[0] |

|[1] |

|[2] |

|[3] |

|[4] |

|[5] |

|[6] |

|[7] |

| |

|J |

|o |

|h |

|n |

|\0 |

| |

| |

| |

| |

|Editing a value inside a String |

|String fname = “John”; |

|fname[2] = ‘X’; // editing element number 2, NOTICE NO CHAR!! |

|System.out.print(“Name: “ + fname + “\n”); // displays “JoXn” |

| |

|[0] |

|[1] |

|[2] |

|[3] |

|[4] |

|[5] |

|[6] |

|[7] |

| |

|J |

|o |

|X |

|N |

|\0 |

| |

| |

| |

| |

Finding a “null” or “” in a String/array of Strings

• you might find that an array element do not contain viable data

• do find, use the “.equals()” string command

• commonly mistaken what to do

|Common search errors |

|String |String in an Array |

| |if(answers[i] != "") { length++; } |

| |if(answers[i] != " ") { length++; } if(answers[i] != null) { length++; } |

| |if(answers[i] != "null") { length++; } |

|Correct null search code |

|String |String in an Array |

|String type = “”; |if(!answers[i].equals("") ) { length++; } |

| | |

|if(answers.equals("")) | |

Getting the String length

• where we had to SET a default value for length, the String class automatically keeps track of the length OF EACH STRING!!!

• return “int” of size value

• THIS TIME IT IS LENGTH()

|[0] |[1] |[2] |[3] |[4] |[5] |

// displays EACH letter of the phrase

for(int i = 0; i < professor.length(); i++)

Concatenation

• adds to END of existing String

o the string will increase in size automatically

• syntax

o final = original + attachment;

String string1 = “Goodbye”; // drawn below

String string2 = “, Cruel ”;

string1

|G |

|Returns |Syntax |

|char |charAt(int index) |

| |          Returns the char value at the specified index. |

| |

|name |

| |

|J |

|o |

|n |

|a |

|t |

|h |

|o |

|n |

| |

| |

| |

|P |

|h |

|i |

|l |

|l |

|i |

|p |

|s |

| |

| |

| |

| |

| |

| |

|int frequency = 0; |

|for(int i = 0; i < name.length(); i++) |

|{ |

|if(name.charAt(i) == ' ') { frequency++; } |

|} // counts # of spaces’s in the name |

Search Methods

|contains methods |

|returns |method |

| boolean |contains(CharSequence s) |

| |Returns true if and only if this string contains the specified sequence of char values. |

| |

|String line = "Mr. Lupoli is a programming professor"; |

| |

|if(line.contains("Lupoli")) |

|{ System.out.println("Yeah, he's in there"); } |

|else |

|{ System.out.println("Nope, not in there"); } |

| |

|String variable = "Munson"; |

| |

|if(line.contains(variable)) |

|{ System.out.println("Yeah, he's in there"); } |

| |

|indexOf method |

| int |indexOf(int ch) |

| |          Returns the index within this string of the first occurrence of the specified character. |

| int |indexOf(int ch, int fromIndex) |

| |          Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index. |

| int |indexOf(String str) |

| |          Returns the index within this string of the first occurrence of the specified substring. |

| |

|String line = "Mr. Lupoli is a programmer professor"; |

|System.out.println(line.indexOf("oli")); |

|System.out.println(line.indexOf('o')); |

|System.out.println(line.indexOf(7, 'o')); |

|// What direction will the search start? |

|// Determine what each display will produce |

|System.out.println(line.indexOf("oli")); |

|// What value will it return? What is it that? |

| |

|if(line.indexOf(variable) < 0){ System.out.println(“item was not found”); } |

|lastIndexOf method |

| int |lastIndexOf(int ch) |

| |          Returns the index within this string of the last occurrence of the specified character. |

| int |lastIndexOf(int ch, int fromIndex) |

| |          Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index. |

| int |indexOf(String str) |

| |          Returns the index within this string of the first occurrence of the specified substring. |

| |

|String line = "Mr. Lupoli is a programmer professor"; |

| |

|// What direction will the search start? |

|// Determine what each display will produce System.out.println(line.lastIndexOf("pro")); |

|System.out.println(line.lastIndexOf('o')); |

|System.out.println(line.lastIndexOf('o', 20)); |

|substring methods |

| String |substring(int beginIndex) |

| |          Returns a new string that is a substring of this string. |

| String |substring(int beginIndex, int endIndex) |

| |          Returns a new string that is a substring of this string. |

| |

|String line = "Mr. Lupoli is a programmer professor"; |

| |

|// Determine what each display will produce |

|String subString1 = line.substring(4); |

|System.out.println(subString1); |

| |

|String subString2 = line.substring(4, 9); |

|System.out.println(subString2); |

Other useful String Methods

| boolean |endsWith(String suffix) |

| |          Tests if this string ends with the specified suffix. |

| String |replace(char oldChar, char newChar) |

| |          Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar. |

| String |replace(CharSequence target, CharSequence replacement) |

| |          Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence. |

| boolean |startsWith(String prefix) |

| |          Tests if this string starts with the specified prefix. |

| boolean |startsWith(String prefix, int toffset) |

| |          Tests if this string starts with the specified prefix beginning a specified index. |

| String |toLowerCase() |

| |          Converts all of the characters in this String to lower case using the rules of the default locale. |

| String |toUpperCase() |

| |          Converts all of the characters in this String to upper case using the rules of the default locale. |

| String |trim() |

| |          Returns a copy of the string, with leading and trailing whitespace omitted. |

What would be the code to LOWERCASE all characters entered name line?

How would you assign a username (first letter, whole lastName) given to string variables fName and lName? (Slip)

Converting a number to a String

int value = 27;

String greeting = “Hello There”;

|H |

|tokenizer.hasMoreTokens( ); |

|determines if more “tokens” in the String |

|used usually in a conditional loop |

|String word = tokenizer.nextToken( ); |

|grabs next token, assigns to “word” |

|records last place it grabbed a word |

|int count = tokenizer.countTokens( ); |

|returns the number of tokens remaining to be returned by NEXTTOKEN() |

Converting Strings to Numbers

There will be many times were the input interface will treat whatever the user types in as a String, (JOptionPane), we can then transform that input into the format intended.

String x;

int real_number;

x = JOptionPane.showDialog(“Enter a whole number:”); // “x” is a STRING 23

realnumber = Integer.parseInt(x); // now “realnumber” is actually an INT value 23

|Type Name |Method for conversion |

|byte |Byte.parseByte(String_to_convert) |

|short |Short.parseShort(String_to_convert) |

|int |Integer.parseInt(String_to_convert) |

|long |Long.parseLong(String_to_convert) |

|float |Float.parseFloat(String_to_convert) |

|double |Double.parseDouble(String_to_convert) |

Breaking down a String

• you can look at individual chars inside a string

• use the char functions to determine what is inside that string

o isLetter

o isDigit

o isWhitespace

o isLowerCase

o isUpperCase

String line = “Goodbye, Cruel World”;

|G |

|int count = 0; |

|for(int i = 0; i < line.length(); i++) // counts # of letters in the string |

|{ |

|if(Character.isUpperCase(line.charAt(i))){ count++; } |

|} |

|System.out.println(count); |

|isDigit example |

|int count = 0; |

|for(int i = 0; i < line.length(); i++) // counts # of numbers in the string |

|{ |

|if(Character.isDigit(line.charAt(i))){ count++; } |

|} |

|System.out.println(count); |

-----------------------

Computer

( stream (

keyboard

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download