Title | CISC1115 Notes - Professor Eva Cogan |
---|---|
Course | Introduction To Programming Using Java |
Institution | Brooklyn College |
Pages | 15 |
File Size | 88.1 KB |
File Type | |
Total Downloads | 92 |
Total Views | 144 |
Professor Eva Cogan...
8/30/18
A class is a blueprint or template for creating different objects that defines properties and behaviors o Give examples from real life o An object is an instance of a class o Every source program includes only one class o We being class names with an uppercase letter o If a class is declared public the name of the source file must match the class name o Note the style
Class header
Open brace at end of line
Close brace at the end of the program under the p
o Body of class is indented
The body of anything is indented one tab
It is standard to use the tab key to indent.
o A method is a named set of statements o A block is 0 or more statements within braces o A string literal is a string of 0 or more characters enclosed in double quotes (what you are used to calling “quotation marks” o Println is a method o System.out.print sends output to the screen
Everything is a Java Application
Every java app has a main method
Escape sequences
The \ is called the escape character and tells the computer to treat it as a special
We can use the escape sequence aka the back slash to print characters
\n is the new line character which takes it to a new line
\t is the tab character
Chapter 2
Write a program to add 2 number /* Name: Add. Java Author: Jamal Description: add 2 numbers and print the result */ public class Add { public static void main (String [] args) { int number 1, number2, sum; number1 = 6; number2 = 7; sum = number1 + number2; System.out.println( “The Sum is “ + sum); } } /* Output
Handcheck
Trace
The Sum is 13
6+7=13
number1 number 2 sum 6
7
13
*/
A variable is a name for a physical location within the computer that can hold one value at a time. As the name implies, the value may change as the program is running
Give meaningful names
Declaration statement tells the computer which variables will be used in the program and what type of values they will hold
A variable of type int will hold an integer
A variable of type string will hold a string of characters Note: the upper case S
Keeping track of the value stored in each value stored in each variable is called tracing a program or producing a memory trace
We can print the value of a variable or an expression
We may declare and initialize a variable at the same time o Int number1 = 6, number2 = 7, sum; Int count, num = 4; //assigns 4 only to num
Suppose you want to store the price of an object in dollars and cents in a variable price. Price cannot have a data type int. to allow for the decimal places, we will declare price to have data type double. This data type allows the variable to hold a real number, one that may contain decimal places. o Double price; o Price = 3.50;
Float was the original. Hardly used anymore. You’ll see it in your workbook
Use double its double the size of float
Division gives decimal: price/2 is 1.75 5th grade division
If either or both operands are double , the division or float
Intro to java syntax
Method A named sequence of statements
Class: for now a collection of related methos
Identifiers o The names of variables, methods, classes, packages and interfaces o A sequence of one or more characters. The first character must be a valid first character (letter,$,_). May also be followed by these or digits o Case sensitive o Style
Variables, methods, keywords, packages use lower camelcase: uppercase only the first character of each word except the first
Classes (and thus files) use upper camelCase: uppercase the first character of each word
Literals
A constant value in java o 100 an integer o 98.6 a floating point value o “this is a string” string
use () o to override precedence. Write y = a/b(+3) to add before dividing o to make a formula clearer o if you aren’t sure of the precedence
parentheses have highest precedence
9/4/18
system is a class that provides methods related to the “system” or environment programs run
a package is a collection of related classes; java.io I/O stands for Input/output
data read by a program can come from 2 places: the keyboard or a data file
the system class also provides a special value System.in
scanner is a class that provides methods for inputting words,numbers, and other data
Scanner is provided by java.util
Import java.util.Scanner; is the main thing to put on top
Import statements can’t be inside a class definition
Create a scanner o Scanner in = new Scanner (System.in); o Declares a scanner variable named in and creates a new Scanner that takes input from System.in; o Often named in, sc, or scanner
Methods o Next – will return what comes before a space
o nextLine – automatically movesthe scanner down after returning the current line o nextInt – will return what comes before a space o nextDouble – will return what comes before a space. Convert to double
Prompts o When the computer waits to read from the keyboard, the cursor blinks on the screen o Program doesn’t continue until user types something o Style: when the prompt and value are short, I put them both on one line
Program Structure o Java.util o Scanner o nextInt o hour = in.nextInt(); o hour*60 o hour
API (Application Programming Interface) o Standard edition of Java comes with several thousand classes
Docs.oracle.com/javase/8/docs/api/
Constants o Final double PI = 3.14159
Formatting output o Use the printf method to specify how values should be formatted
o Following comman displays price with 2 digits after decimal point
System.out.printf (“&.2f”. price);
You can also specify a field width
System.out.printf(“%10.2f”, price)
The construct %10.2f is called a format specifier
“Hello%nWorld%n” Hello/World
Printf does not print to a new line, for new line use \n
Casting o Convert a floating point value to an integer is to use a type cast
Double pi = 3.14159;
Int x = (int) pi;
o Type casting takes precedence over arithmetic operations it only applies to what follows immediately
To solve nextLine being skipped after being asked age YOU MUST ADD A NEW nextLine TO SOLVE THE PROBLEM
9/6/18
Standard input o System.in
Standard Output o System.out
Standard Error o System.err
Reading / Writing
o Import java.io.File; o Import java.io.PrintStream; o And add public static main (String [] args) throws Exception { o Try statement catches and handles the exception o Throws clause is that lists the exception
An Exception is an event, which occurs during the program
Print to a file o Import. java.io.PrintStream; Import java.util.Scanner; Public class PrintToFile { Public static void main(String[] args) throws Exception { String first, last Scanner sc = new Scanner (System.in); PrintStream ps = new PrintStream (“Output.txt”); PrintStream ps = new PrintStream (newFile(“output.txt”)); System.out.println(“Please Enter your First and Last Name.”); Syste,.out.println(“Do not forget to press the enter key.”); First = sc.next(); Last = sc.next(); ps.println(“\nThis ismy First Program!”); ps.println(“My Name is: “ + first + “” + last); ps.close(); }
}
Know how to read all versions o Note new File in new Scanner o Could put new File in PrintStream, too o Could also use PrintWriter instead of PrintStream o Should close file using ps.close(); User defined methods
o A module is a series of instructions with one specific purpose. A module can be written directly in the main program or we can write a method that consists of the named module o Methods can be called anytime throughout the program o A method can be called within main and another method can be called again 9/13/18
Parameters and Arguments o Methods are possessive o Main has an n
Try to add one has an n
Value inside main method does not affect other n inside other methods
Multiple Parameters o Every time you call a method, you rewrite its trace from the beginning o The parameters and local variables exist only while the method is executing and are destroyed when you return to the calling method
o Parameters are matched by position, not by name o Call by value: in method java method arguments are passed by value o Before each method, put a comment saying what it does
Increment operator o Java provides a more concise way to add and subtract by one. Specifically ++ is the increment o Decrement is –
9/20/18
Assignment operators have lowest precedence and associate right to left.
Booleans are variables that can hold both true and false
A conditional if statement allows a program to branch, which means to allow the path of execution depending on the value
In a conditional statement, the keyword if is followed by some condition (in parentheses) that evaluates to either true or false
Three rules o If true, execute o If false, ignore o If more than one statement in the body, enclose the block of statements in curly braces{}
Style o If its only one statement, I don’t put braces some people do o Put the open brackets at the end f the header and the close brace under the ‘I’
o Put the if condition on one line and the body on the next line, indented one tab position (like the body of anything)
Note: o Indent one tab for body o Braces if the body is a block of compound statements o No ; after else
9/27/18
The chained If-else o We can use a chain of if-else construction o Java lets you chain multiple if-else statements together for situations where you need to choose one of multiple statements to execute o Quit as soon as we find a match o Simplest form of a chained if
If cond1 is true, it does st_1
If cond1 is false and cond2 is true, st 2 is executed
If cond1 is false and cond2 is false, st_3 is executed
St 4 is always executed
Dangling if-else o An else statement is associated with the closest preceding unmatched if. Use {} to enforce what you mean
For loop o For(int I = 1, i...