Sie sind auf Seite 1von 18

CS 151 - All Notes - Starting Out

With Java
Brief Review
Chapter 2
order of precedence
unary negation - right to left
multiplication/division/modulus - left to right
addition/subtraction - left to right
write mathematical statement
primitive data types and size in bytes
how to represent a character, string, boolean types
primitive data types
modulus question - remainder/division
casting operators
section 2.8 - named constant
read in char
Chapter 3
define class and object - 1.3
creating driver
private and public access modifiers
mutator method - modifies instance fields
accessor method - retrieves instance fields
define constructor with properties
stale data
pass by value - passing copy or value
pass by reference - passing address
difference between no-arg and default constructor
UML class diagram: class name, attributes, methods
Chapter 4
if, if else, conditional
random class
make sure if-else charts look right
Chapter 5
writing data
reading data
Chapter 6
use quiz online
enumerated types
static types
overloaded types
toString method
Chapter 2
//Add using scanner
//name = keyboard.nextLine();
import java.util.Scanner
public Add {
public static void main(String[] args) {
int int1, int2, sum;
string
Scanner keyboard = new Scanner(System.in);
System.out.println(Please type in the 1st number.);
int1 = nextInt();

System.out.println(2nd number now please.);
int2 = nextInt();
sum = int1 + int2;
System.out.println(The sum is + sum + of the 1st and 2nd number typed in.;
}
}
//This is a simple Java program.
public class Simple {
public static void main(String[] args) {
}
}
\n - new line - advances cursor to next line for subsequent printing
\t - tab - causes cursor to skip over to next tab stop
\b - backspace - causes cursor to back up, or move left, 1 position
\r - carriage return - causes cursor to go to beginning of current line, not next line
\\ - backslash - causes backslash to be printed
\ - single quote - single quotation mark is printed
\ - double quote - double quotation mark is printed
Must store with .java file extension, and name file as a public class
variable names should begin with a lower case letter and then switch to title case
thereafter: int caTaxRate
class names should all be title case: public class BigLittle
primitive data types: byte, short, int, long, float, double, boolean, char
String str = keyboard.nextLine();
char myChar = str.charAt(0);
Primitive Data Types
byte 1 byte
short 2 bytes
int 4 bytes
long 8 bytes
float 4 bytes
double 8 bytes
Chapter 3
String myString = Hampton University
myString.toUpperCase();
myString.charAt(2); -> m"
int x = 4 * 3.1
int x = (int)
char letter = A;
String Constructor
String name = new String(Michael Long);
Vocabulary
String - class
name - object name
new - allocates memory
no-arg - no parameters, boolean defaults, numeric values to 0, strings set to null
default - when you dont define own constructor, this default is created
class - A blueprint for the program that acts as a named storage location within the
computer's memory that is composed of certain attributes and methods that are used to
describe a particular object; blueprint of object that specifies attributes & methods for that
particular object
object - An instance of a class that acts as a software component existing in memory that
serves a specific purpose in the program and was created from a class that contains code
describing that particular object; instance of that class
constructor - What initializes an object's attributes and methods with appropriate data and
performs any necessary setup operations
constructor special properties - no return type (not even void), typically public, may not
return any value, same name as class
encapsulation - encloses proper attributes and methods within a single class
private access modifier - member cannot be accessed by code outside of the class
public access modifier - any one can access it outside or inside class
primitive data types - float, int, byte, long, double
reference data types - string
object: object is an instance of a class that describes the object using code; software
component existing in memory that serves a specific purpose in program
class: code that functions as a sort of blueprint to describe a particular tip elf object
through programming statements composed of attributes/fields or operations for that
object
string: sequence of characters enclosed with double quotation marks
Class - blueprint of an object
Driver - program that controls the operation of a device such as a printer or scanner.
Need to Know
Primitive data types
Define double with value of 3.56
Values boolean variable can hold
import Scanner statement
create scanner object
complete program structure for java program
two ways to create comment // and /* */
combined operator assignment statements
why is reference variable different from a primitive data type? because reference variables
hold address of that object
constructor method that is automatically called when an instance of a class is created.
import statement tells the compiler in which package a class is located.
all arguments of the primitive data types are passed by value
6 * 4 - 15 % 6 * 3 - 4 = 23
// have to include default settings for no arg constructor
public retail() {
description = null;
units = 0;
price = 0;
}
//driver le
Rectangle r = new Rectangle(); //creating object
r.setWidth(10); // setting value
r.setLength(10);
System.out.println("Width: " + r.getWidth());
System.out.println("Length: " + r.getLength());
System.out.println("Area: " + r.getArea());
} }
//class le
public class Rectangle {
private double width; // defining attributes
private double length;
//call methods are mutator, accessor, calculated
public void setWidth(double w) { // mutator methods modify or change attributes/fields
width = w;
}
public void setLength(double l) {
length = l;
}
public double getWidth() { // accessor methods allow user to see values/attributes but cannot
modify them
return width;
}
public double getLength() {
return length;
}
public double getArea() { // calculated method returns result of calculation
return width * length;
} }
UML (unied modeling language) Diagram
Name
Rectangle
Attributes
width: double
length: double
Methods
Constructor - Rectangle(len:double, w:double)
setWidth(w:double) :void
setLength(len: double) :void
getWidth() :double
getLength() :double
public class Student {
private String SName, Smaj;
private int SID;
//constructor with multiple arguments
public Student(String st_name,int st_id, String maj) {
//list private variables first then parameters
SName = st_name;
Smaj = maj;
SID = st_id;
}
//example of no arg constructor automatically created for you if none created yet
public Student() {
SName = ;
Smaj = ; //null for strings
SID = 0;
}
//set methods used to create empty constructor
//know 3 types of constructors
}
Driver
//driver contains main method only
//1st method:
String myName, myMajor;
int myID;
//2nd method:
myName = Jean;
myMajor = CSC;
myID = 1234;
//Student(myName,myID,myMajor);
//must match order of parameters entered
//3rd method:
//Read from keyboard
Read till there is no more data
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
class BetterQuoteReader {
public static void main(String args[]) throws IOException {
Scanner fileScanner = new Scanner(new File("funny_quotes.txt"));
while (fileScanner.hasNext()) {
System.out.println(fileScanner.nextLine());
}
}
}
Reading different types from a File
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
class EmployeeInfoReader {
public static void main(String args[]) throws IOException {
String name;
String title;
double salary;
Scanner fileScanner = new Scanner(new File("employee_info.txt"));
while (fileScanner.hasNext()) {
name = fileScanner.nextLine();
title = fileScanner.nextLine();
salary = fileScanner.nextDouble();
fileScanner.nextLine();
System.out.printf("%s, %s, %.2f\n", name, title, salary);
}
}
}
Chapter 4
some of checkpoint and review question exercises included
relational operators
take an if statement and draw flow chart
if statement
if else
nested if
truth tables
and - && (Truth Table: T, F, F, F)
or - || (Truth Table: T, T, T, F)
not - !
comparing strings
if (string1.equals(string2)) //not ==
conditional operators
x > y ? z = 10 : z = 5;
switch statements

random class
import java.util.Random;
Random rand = new Random();
number = rand.nextInt(6) + 1; //for dice
flag, boolean variables
long methods can be broken up into shorter segments called helper/utility methods
nextInt(int n) //generates number that goes from 0 to n
import java.util.Random;
int number;
Random randomNumbers = new Random(); //create a random object
number = randomNumbers.nextInt(); //get a random integer and assign it to number
number = randomNumbers.nextInt(10) + 1; //this generates 0-10
number = randomNumbers.nextInt(10) //this generates 0-9
order of precedence with symbols
!
&&, ||
<, >
Parenthesis can be used to force the precedence to be changed
Overall Order of Precedence
!
* / %
+ -
< > <= >=
== !=
&&
||
= += -= *= /= %=
Reference variables contain the address of the object they represent
equals, compareTo methods (case sensitive)
equalsIgnoreCase or compareToIgnoreCase
Variable scope
Local variable doesnt have to be declared at beginning of method
Scope of local variable begins at point it is declared and terminates at end of method
Variable in scope means that variable visible to program
Conditional Operator
ternary operator
works like an if-else statement
can also return a value
expression1 ? expression 2 : expression 3
if this is true, do this, else do this
example: x > y ? z = 10 : z = 5;
which means if x is greater than y than make z = 10, else z = 5
number = x > y ? 10 : 5
Switch Statement - allows you to use an ordinal value to determine how program will
branch
can evaluate an integer or character type and make decisions based on value
works like an if-else if statement
char, byte, short, int, String can be used for switch statements
break statements ends case statement and is optional
default is optional
import java.text.DecimalFormat;
can format full fractional values
if statements - decides whether a section of code execute s or not, uses boolean to decide
whether next statement executes
if ( x > 5 )
print x;
if (coldOutside) {
wearHat();
wearCoat();
wearGloves();
}
multiple statements require brackets, single statements do not
>= greater than or equal to
<= less than or equal to
x++ -> incrementing x by 1
if (x>y) {
x ++;
y += 3;
}
y++;
x = y;
MUST indent always with if statements for syntax clarity
flag - boolean variable that monitor some condition in a program
when condition is true, flag is set to true
flag can be tested to see if condition has changed
if (average < 95)
highScore = True;
if (highScore)
System.out.println(thats a high score!);
unicode stored as 16 bit #
characters are ordinal (order in unicode character set)
meaning they can be compared to each other
char c = A;
if (c < Z)
System.out.println(A is less than Z);
if (str1.equals(str2)) //str1 == str2 DOES NOT WORK
println str1;
else
println str2;
Nested if else statements
if (x > 5) {
if (y < 4)
print y;
else
print x;
}
else {
if (z == 4)
print z;
else
print x;
}
//dont forget to initialize variables
int x = 5;
int y = 10;
int z = 5;
Comparison Operators
and - && (Truth Table: T, F, F, F)
or - || (Truth Table: T, T, T, F)
not - !
double val = Math.sqrt(25.0);
Chapter 5
number = number + 1; > number++; or ++number;
number = number - 1; > number-- or --number;
Prex
int x = 1;
System.out.println(x); > 1
System.out.println(++x); > 2
Postx
System.out.println(x++); > 1
System.out.println(x); > 2
while Loop - pretest, innite loop - a while loop may never execute if its initially false
System.out.println(Enter a number in the + range of 1 through 100: );
number = keyboard.nextInt();
while (number < 1 || number > 100) { //make it && to hack it to make invalid
System.out.println(That number is invalid.
System.out.println(Enter a number in the + range of 1 through 100: );
number = keyboard.nextInt();
}
do-while Loop - post test loop - executes loop prior to testing condition - going to run at
minimum 1 time, need to make condition false > otherwise, innite loop
do {
int x = 5;
} while()
System.out.println(x);
int x = 5;
do {
System.out.println(++x); //x++ > executes 6 while ++x > executes 5
} while(x < 6);
for loop pretest loop
for (int x = 0; x <= 5; x++) { //prints out first 6 numbers
System.out.println(x);
}
for (int x = 0; x < 5; x++) { //prints out first 5 numbers
System.out.println(x);
}
for (int x = 0; x < 5; x += 2) { //prints out 0, 2, 4, 6
System.out.println(x);
}
for (int x = 0; x < 100; x += 7) { //prints out numbers 0 - 100 in increments of 7
System.out.println(x);
//can also be written as while loop
int x = 0;
while (x < 100) {
System.out.println(x);
x += 7;
}
for (x = 100; x > 0; x --) { //printing out numbers in reverse
System.out.println(x);
}
for (;;){
System.out.println(x); //infinite loop
}
Writing Files
import java.io.*
public static void main (String[] args) throws IOException {
PrintWriter output file = new PrintWriter("names.txt");
outputFile.println(line 1);
outputFile.close();
}
Reading Files
// Open the file.
File file = new File(Names.txt);
Scanner inputFile = new Scanner(file);
// Read a line from the file.
String str = inputFile.nextLine();
// Close the file
inputFile.close();
Appending Text To A File
FileWriter fw = new FileWriter (name.txt, true);
PrintWriter fw = new PrintWriter(fw);
Detecting End of File
//Open file
File file = new File(filename);
Scanner inputFile = new Scanner(file);
// Read until the end of the file
while (inputFile.hasNext()){
String str = inputFile.nextLine();
System.out.println(str);
}
inputFile.close(); //close file when done
Use \ to include (strings) or +
PrintWriter outFile = new PrintWriter(/home/rharrison/names.txt);
number = number + 1; > number++; or ++number;
number = number - 1; > number or --number;
int x = 1;
System.out.println(x); > 1
System.out.println(++x); > 2
System.out.println(x++); > 1
System.out.println(x); > 2
import java.io.*
public static void main (String[] args) throws IOException
PrintWriter outputFile = new PrintWriter(filename);
outputFile.println(line1);
outputFile.close();
File file = new File(filename);
Scanner inputFile = new Scanner(file);
while (inputFile.hasNext()) {
String str = inputFile.nextLine();
System.out.println(str);
}
inputFile.close();
1 Program Different Loops
while Loop
int count = 1;
double sum = 0;
while (count <= 5) {
System.out.println(enter grade: );
int grade = keyboard.nextInt();
sum += grade;
count++;
}
System.out.println(Average: + (sum/5));
do-while Loop
int count = 1;
double sum = 0;
do {
System.out.println(enter grade: );
int grade = keyboard.nextInt();
sum += grade;
count++;
} while (count <= 5)
for loop
double sum = 0;
for (int i; i<= 5; i++) {
System.out.println(enter grade: );
int grade = keyboard.nextInt();
sum += grade;
}
System.out.println(Average: + (sum/5));
Chapter 6
public int add(int num1, int num2) {
int sum = numl + num2;
return sum;
}
public String add(String str1, String str2) {
String combined = strl +str2;
return combined;
}
Vocabulary
overloading: 2 or more methods with same name but different signatures; multiple
methods in same class have same name, but use different types to parameters
method signature: name, type of parameters, order of parameters - to determine which
method to call
toString Stock xyzCompany = new Stock(XYZ, 9.62);
EXPLICITLY System.out.println(xyzCompany.toString());
NON-EXPLICITLY System.out.println(xyzCompany);
enum type
SYNTAX enum typeName { one or more enum constants }
DEFINITION enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY,
FRIDAY, SATURDAY }
//capitals not needed but preferred, defined between class and main method,
ordinal numbers are SUNDAY = 0, MONDAY = 1, and so on
DECLARATION Day WorkDay;
ASSIGNMENT Day WorkDay = Day.WEDNESDAY;
ask what kind of methods it is but return type does not matter so not overloaded type
same name, same parameters, different return types - error, because parameter list is same
static fields shared with all objects
instant fields - each object has own copy - not shared
calling method in static class versus non-static class - what is difference?
not tied to an object in static -> Math.pow(2.0, 3.0)
you have to tie method to object in non-static class -> ob1.getName();
copyright FVCproductions 2014

Das könnte Ihnen auch gefallen