Chapter 2: The Basics of C++ Programmingfaculty.cse.tamu.edu/slupoli/notes/Java/AdvIntroJava... ·...
Transcript of Chapter 2: The Basics of C++ Programmingfaculty.cse.tamu.edu/slupoli/notes/Java/AdvIntroJava... ·...
Intro. to Java Programmingfor Adv. Programmers
Hats I will wear this semesterYou Me
The SEVEN sections of a program Introduction/Name of ProgramImport statements/Preprocessor commandsclass headerclass variablesFunctionsmain( )class closer
1
Part 1: Introduction/Name of Program
Your name, class, and program name and a brief description of the programExample: //Ryan Dorrill //C++ AB //BlackjackPart 2: Import statements/Preprocessor commands
Commands that include other library files, those files contain commands, functions, etc…
import javac.swing.* // common library to includePart 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: Functionsfunctions/procedures that help the MAIN program run.Main calls these functions created here.Part 6: Main programThe 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
2
Input and OutputI/O stream
sc.nextDouble( ) System.out.println( )sc.nextInt( ) System.out.print( )
Printing a Line of TextPrint 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 variablesint x = 0; // MUST DECLARE ALL VARIABLE BEFORE USINGint y = 8;
System.out.println(“X is: “ + x + “ and Y is: “ + y );
3
Computer
keyboard
stream
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
o Keyboard è System.inThe Scanner’s Purpose and Creation
System.in (Keyboard)Scanner sc = new Scanner(System.in);
int score = sc.nextInt();...
Scanner Important Information Must import
o java.util.Scanner; Scanner will ignore white spaces BEFORE a value, but BY DEFAULT will
STOP:o At a white space (those not reading in a line)o 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
4
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
o INDENTIFY what exactly you wish to read in o 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
o next() (reads value)o 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)
5
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.
6
Input/Output Homework Exercise
String name, address; // declare ALL variables before you use them// string is used for STRING textScanner 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!!
7
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 = sizeindex 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 Computero called garbage!!!o good to set value (below) to your choice of a default
type [] arrayname = new type[size];
8
Declaration of Multiple datatype arraysDouble 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 arraysDouble Integer String Char//… declared here!!!
double sodaPrice[0] = .65;// incorrect code
sodaPrice[0] = .65;sodaPrice[1] = .85;sodaPrice[2] = .75;
//… declared here!!!
seasonPts[0] = 13;seasonPts[1] = 14;seasonPts[2] = 8;seasonPts[3] = 25;seasonPts[4] = 3;…seasonPts[12] = 26;
//… declared here!!!
names[0]= “Lupoli”;names[1]= “Akman”;names[2]= “Jensen”;names[3]= “Harman”;names[4]= “Martino”;names[5]= “Reardon”;…names[24]= “Myers”;
names[1] = “Munson”;
//… declared here!!!// …
alphabet[0] = ‘A’;alphabet[1] = ‘B’;alphabet[2] = ‘C’;…alphabet[25] = ‘Z’;
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?
9
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 arraysDouble Integer String Char//…
System.out.println(sodaPrice[0]);System.out.println(sodaPrice[1]);System.out.println(sodaPrice[2]);
same as String [] names = new String[25];// …
System.out.println(names[0]);System.out.println(names[1]);System.out.println(names[2]);System.out.println(names[3]);System.out.println(names[4]);…System.out.println(names[24]);
// …
System.out.println(alphabet[0]);System.out.println(alphabet[1]);System.out.println(alphabet[2]);…System.out.println(alphabet[26]);
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 arraysint [] 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
10
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 LoopsNon-loop Loop
int test = new int[10]; // 10 test scores
// after values are placed
System.out.println(test[0]);System.out.println(test[1]);System.out.println(test[2]);System.out.println(test[3]);System.out.println(test[4]);System.out.println(test[5]);…System.out.println(test[9]);
int test = new int[10]; // 10 test scores
// after values are placed
for(int i = 0; i < test.length; i++) { System.out.println(test[i]);}
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 useDouble 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)
11
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 literalo 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 InitializationGathering values into Strings Example 1
String firstName = “”, lastName = “”;firstName = sc.next (); // input: Mr. LupolilastName = sc.next ();System.out.print(lastName + “, “ + firstName); // output: Lupoli, Mr.
12
firstName lastName
Gathering values into Strings Example 2String firstName = “Kristen”;String lastName = “Davis”;System.out.print(lastName + “, “ + firstName); // output: Davis, Kristen
firstName lastName
13
M r . L u p o l i
K r i s t e n D a v i s
Gathering values into Strings Example 3String wholeName = “”;wholeName = sc.nextLine(); // input: Mr. LupoliSystem.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 == , <=, >=, !=, >, <. etc… compareTo
o compares two stringso method returns a value
== 0 (match) < 0 no match, S1 is alphabetically less than S2 > 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
14
compareTo
// compareTo exampleString testOne = "Lupoli";String testTwo = "Martino";
if(testOne.compareTo(testTwo) < 0){ System.out.println("testOne is LESS than testTwo"); }else if(testOne.compareTo(testTwo) > 0){ System.out.println("testOne is GREATER than testTwo"); }else // (testOne.compareTo(testTwo) == 0){ System.out.println("testOne is EQUAL to testTwo");}
if(testOne.compareTo("Lupoli") == 0){ System.out.print("Strings matched"); }
equal
// equal exampletestOne = "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 StringString 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
15
Editing a value inside a StringString 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 errorsString 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 codeString String in an Array
String type = “”;
if(answers.equals(""))
if(!answers[i].equals("") ) { length++; }
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()
// displays EACH letter of the phrasefor(int i = 0; i < professor.length(); i++)
[0] [1] [2] [3] [4] [5]L u p o l i
16
Concatenation adds to END of existing String
o the string will increase in size automatically syntax
o final = original + attachment;
String string1 = “Goodbye”; // drawn belowString string2 = “, Cruel ”;
string1G o o d b y e
string1 = string1 + string2;
string1G o o d b y e , _ C r u e l _
string1 = string1 + “World!”; // literal string
string1G o o d b y e , C r u e l W o r l d !
Determine what “answer” will look like after the code below:
1. String string1 = “Goodbye”; // drawn below2. String string2 = “, Cruel ”; 3. String answer;4. answer = answer + string1;5. answer += string2; // hmmm, think about it!!6. string1 = “Lupoli”;7. answer = answer + string1;8. System.out.println(answer); // put answer below (if not already!)
answer
17
Char at returns a CHAR value from a specific AND single location in the string great for grabbing the FIRST letter of a first name for a username usually in if statements and for loops great for counting spaces
charAt() functionReturns Syntaxchar charAt(int index)
Returns the char value at the specified index.
name
int frequency = 0;for(int i = 0; i < name.length(); i++){
if(name.charAt(i) == ' ') { frequency++; }} // counts # of spaces’s in the name
Search Methodscontains 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))
18
J o n a t h o nP h i l l i p s
{ 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 produceSystem.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));
19
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 produceString 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?
20
How would you assign a username (first letter, whole lastName) given to string variables fName and lName? (Slip)
Converting a number to a Stringint value = 27;String greeting = “Hello There”;H e l l o T h e r e
String complete = greeting + value; // just the same as concatenation of 2 Strings!!H e l l o T h e r e 2 7
String Tokenizer import java.util.StringTokenizer; breaks input line into a sequence of Strings (words) separated by spaces CANNOT TOKENIZE INDIVIDUAL LETTERS (use .charAt( )) this String below was read in using sc.readLine( );
M r . L u p o l i i s d a b o m b
tokens(separated by spaces)
String inputline = sc.readLine( );StringTokenizer tokenizer = new StringTokenizer(inputline);
Other tokenize functionstokenizer.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()
21
Converting Strings to NumbersThere 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 23realnumber = Integer.parseInt(x); // now “realnumber” is actually an INT value 23
Type Name Method for conversionbyte 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 isLettero isDigito isWhitespaceo isLowerCaseo isUpperCase
String line = “Goodbye, Cruel World”;
G o o d b y e , C r u e l W o r l d ! \0√ √ √ √ √ √ √ √ √ √ √ √ √ √ √ √ √Total = 17
isLetter exampleint count = 0;for(int i = 0; i < line.length(); i++) // counts # of letters in the string {
if(Character.isUpperCase(line.charAt(i))){ count++; }}
22
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);
23