Java Quick Ref

advertisement
Java Reference Guide(Chapters 1-7)
Page 1
3/6/2016
Syntax
Example statements
type variableName;
or
type variableName = value;
final type name = value
Assignment
statements
variable = value to store;
Method Call
(return and display)
Method Call
(store return value)
Method Call
(no return)
Import class
Construct object
System______(object.method(parameters));
int numberItems;
String greeting = "hello";
Class
public static final double TAX_RATE = .07;
Method final double TAX_RATE = .07
score = 10;
total = total + newItem;
running total
count = count + 1;
counter
count++ ;
shortcut for adding 1
System.out.print(“Balance = “ + larry.getBalance());
type variable = object.method(parameters);
double grade = course.calculateGrade();
object.method(parameters);
Display output
System.out.println( ); new line
System.out.print( );
print on same line
(cast type) variable;
harrysChecking.deposit(500);
line.determineLineType();
import java.awt.Rectangle;
Rectangle box = new Rectangle(5,10,20,30);
Payroll john = new Payroll(name,payRate,hours)
System.out.println("Area = " + area);
System.out.print("X = " + r1.getX( ));
average = (double) totalScores / NumberScores;
Define local variables
Define constants
Cast
import packageName.className;
class variable = new constructor(parameters);
Common Data Types
Type
int
long
double
char
boolean
String
Use
Small Whole numbers
Large whole numbers
Decimal values
Single character value (char values are put in ' ')
Storing true or false; Use when making decisions in if statements
Storing words (Note: String is really a class) – put strings in " "
Math Operators
+ Add
– Subtract
* Multiply
/ Divide
% Mod (return remainder) 13 % 5 = 3
Order of Operations (PEMDAS)
Strings
Action
Convert string input to integer
Convert string input to floating-point
Find length of string variable and store in variable
Extract part of the string value
Compare 2 strings
Check to see if 1 string is contained inside another string
Example
int count = Integer.parseInt(input)
double price = Double.parseDouble(input)
int numChars = message.length()
Message = "Hello World" (numbered 0 – 11)
message.substring(6,9) = "Wor" (start, end)
response.equals(“Y”)
response.equalsIgnoreCase(“Y”)
vowels = "aeiou"
testString = "a"
vowels.indexOf(testString)
Returns -1 if not found
Math Methods and Constants
Constant or Method
Math.PI
Math.pow(x,n)
Math.sqrt(x)
Math.abs(x)
Math.round(variable)
Description
Constant value for pi
Finds Xn
Finds square root
Finds absolute value
Round to nearest integer
Math.pow(2,4) = 24 = 16
Math.sqrt(16) = 4
Math.abs(-8) = 8
(int)Math.round(12.64) = 13
Common Classes to Import
Class
java.util.Scanner
javax.swing.* and java.awt.*
java.util.Random
java.text.*
What it is for
Scanner for input to console window
Java graphics
Random number generator
formatting
Java Reference Guide(Chapters 1-7)
3/6/2016
Page 2
GETTING INPUT FROM USER – USING SCANNER
Code
import java.util.Scanner;
Scanner in = new Scanner(System.in);
System.out.println(“Enter the _________: “);
double price = in.nextDouble();
int quantity = in.nextInt();
String address = in.nextLine();
String state = in.next();
What it does
Includes the scanner class
Construct a scanner to use for getting input
Prompt user for data to enter
Get a decimal value and store in a variable
Get an integer and store in a variable
Get line of text and store in a variable
Get 1 word and store in a variable
GETTING INPUT FROM USER AND SHOWING MESSAGES – USING JOPTIONPANE
Code
import javax.swing.JOptionPane;
String input = JOptionPane.showInputDialog(null, "Enter
quantity: ", "Quantity", 1);
double price = Double.parseDouble(input);
int quantity = Integer.parseInt(input);
JOptionPane.showMessageDialog(null, "Invalid entry. Try
again.", "ERROR", 1);
System.exit(0);
What it does
Includes the JOptionPane class
Prompt user for data to enter
The parameters: null, Prompt message, Title of Box, 1
Change string input value to a double value
Change string input value to an integer value
Show error message
You must have this line at end of code when using JOption
FORMATTING OUTPUT
Code
import java.text.*;
DecimalFormat formatMoney = new DecimalFormat("$#,###,##0.00");
DecimalFormat formatPercent = new DecimalFormat("##%");
DecimalFormat formatGeneral = new DecimalFormat("###,###,##0.0");
System.out.println("Bill is " + formatMoney.format(register.getBill());
System.out.println("Bill is " + formatMoney.format(bill));
What it does
Includes the class needed for formatting
Formatter for money
Formatter for percents
Formatter for general numbers
Display money amount using a getter
Display money amount using a local variable
GENERATING RANDOM NUMBERS
Code
import java.util.Random;
Random generator = new Random();
int die = generator.nextInt(6) + 1;
double number =generator.nextDouble( );
What it does
Includes the class needed for formatting
Construct a random number generator
Get an integer from 1-6
Return a decimal value from 0 to 1.
IF STATEMENTS
Relational Operators
>
Greater Than
>= Greater Than or Equal To
<
Less Than
<= Less Than or Equal To
= = Equal to
(remember, assignments use just 1 =)
!= Not Equal to
if/else statement
if (amount < 0)
System.out.println("Error");
else
{
balance = balance + amount;
System.out.println("Amount has been deposited.");
}
if/else/if (use to compare variable to a list of values)
Check grade and display A, B, or C
Logical Operators
And
&& both must be true
Or
||
only 1 has to be true
Not
!
Nested If Statements
if (isBattleshipHit())
{
if (isShipSunk())
System.out.println(“You sank my battleship”);
else
numberHits++;
}
else
System.out.println(“You missed.”);
switch (use only with type int and char)
Check answer to a question
Java Reference Guide(Chapters 1-7)
if (grade >= 90 && grade < = 100)
System.out.println("A");
else if (grade >= 80 && grade <= 89)
System.out.println("B");
else if (grade >= 70 && grade <= 79)
System.out.println("C");
Check Number of Copies and Determine Cost
if (copies >=1 && copies <= 100)
cost = copies * .10;
else if (copies >=101 && copies <= 199)
cost = copies * .05);
else if (copies >= 200 && copies <= 299)
cost = copies * .03;
else
System.out.print("Please enter a number 1-299");
Page 3
3/6/2016
switch(answer)
answer is of type char
{
case 'A':
System.out.println("Correct");
correct = correct + 1;
break;
case 'B':
System.out.println("Incorrect");
break;
case 'C':
System.out.println("Incorrect");
break;
default:
System.out.println("Choose A, B, or C");
break;
}
LOOPS
For Loop
for (int x = 1; x <= 10; x++)
body
counts 1 to 10
Do While Loop (to validate input)
do
{
Get input
if (bad input values)
Display error
}
while (bad input values);
While Loop
while(condition)
body
-while this condition is true do the body
While Loop (using Sentinel value)
boolean done = false;
Q is sentinel in this example
while(!done)
{
Get input
if (input.equalsIgnoreCase("Q"))
done = true;
else
{
change input to numeric value
continue processing the input value as needed
}
}
Nested loop to process 2D tables
for (int row = 1; row <= #rows; row++)
{
do whatever is needed for beginning of a row
for (int col = 1; col <= #cols; col++)
do what is needed for a column
do what is needed after all columns in row are done
}
Chapter 7 – Arrays and ArrayLists (to use ArrayList import: java.util.ArrayList)
Action
Define array
Get length of array
Access an element in array
Define ArrayList
Add object to ArrayList
Get length of ArrayList
Access an object in ArrayList
Remove element in ArrayList
ArrayList of numbers
Define a 2 dimensional array
Example statements
double[ ] scores = new double[10];
scores.length;
scores[5] = 94;
ArrayList<BankAccount> accounts = new ArrayList<BankAccount>();
students.add(“Joe Cool”);
accounts.size();
accounts.get(0);
accounts.remove(3);
ArrayList <Double> measurements = new ArrayList<Double>();
String[][] board = new String[3][3];
Java Reference Guide(Chapters 1-7)
Page 4
3/6/2016
EXAMPLE CLASS DIAGRAM
BankAccount
– balance:double
+ INTEREST_RATE:double = .07
+ getBalance( ):double
+ deposit(double amount):void
+ withdraw(double amount):void
– variable name: type
+ constant name: type = value
+ method(parameters):type
– private
+ public
EXAMPLE CONSTRUCTORS
/**
* Constructs a bank account with zero balance.
Document the constructor’s purpose
*/
public BankAcount( )
CONSTRUCTOR-assign default values
{
balance = 0;
}
---------------------------------------------------------------------------------------------/**
* Constructs a bank account with an initial balance.
Document constructor’s purpose
* @param initialBalance the starting balance for account
*/
public BankAcount(double initialBalance)
CONSTRUCTOR-assign user value's
{
balance = initialBalance;
}
EXAMPLE METHODS
GETTER (returns, no parameters)
/**
* Gets current balance of the bank account.
* @return the current balance
*/
Document the method's purpose
Document the return value
public double getBalance()
{
return balance;
}
MUTATOR (no return, with parameters)
/**
* Withdraws money from the bank account.
* @param amount amount of money to withdraw
*/
public void withdraw(double amount)
{
balance = balance - amount;
}
Document the method's purpose
Document each parameter
MUTATOR (no return, no parameters)
/**
* Determine type of line.
*/
public void determineLineType()
{
if (rise == 0)
lineType = ‘H’;
else if (run == 0)
lineType = ‘V’;
else
lineType = ‘S’;
}
Document the method's purpose
Java Reference Guide(Chapters 1-7)
CLASS DEFINITION
accessSpecifier class ClassName
{
constructor
methods
fields(variables)
}
3/6/2016
EXAMPLE
public class BankAccount
{
//-------------------------constructors-------------------------public BankAccount(double initialBalance) {…code… }
//-------------------------methods-------------------------------public void deposit(double amount) {…code…}
//-----------------------instance variables---------------------private double balance;
}
CONSTRUCTOR DEFINITION
EXAMPLE
accessSpecifier Class(parmType parmName, …)
{
constructor body – initialize instance variables
}
public BankAccount(double initialBalance)
{
balance = initialBalance;
}
METHOD DEFINITION
accessSpecifier returnType methodName(parameterType parameterName, …)
{
method body
}
Example Method No Return
public void deposit(double amount)
{
balance = balance + deposit;
}
INSTANCE FIELD DECLARATION
accessSpecifier fieldType fieldname;
Example:
private double balance;
Method with Return____
public double getWidth( )
{
return width;
}
always put private

public – any code anywhere can access the public feature
Use public for: classes, constants, methods, and most constructors

private – only code within the same class can access the private feature
Use private for: all instance variables and for methods you don’t want outside code to be able to call
Page 5
Java Reference Guide(Chapters 1-7)
Page 6
3/6/2016
EXAMPLE CLASS
BankAccount
– balance:double
+ MAX_WITHDRAW:double = 300
+ getBalance( ):double
+ deposit(double amount):void
+ withdraw(double amount):void
– var name: type
+constant name: type=value
+ method(parameters):type
– private
+ public
+ public
import java.___.____
MUST PUT IMPORT LINES ABOVE CLASS COMMENT
/**
* A bank account has a balance that can be changed by deposits and withdrawals.
Document the class's purpose
* @author Mr. Moon
* @version 2/20/06
*/
public class BankAccount
START OF THE CLASS
{
-------------------------------CONSTRUCTORS--------------------------------------/**
* Constructs a bank account with zero balance.
Document the constructor’s purpose
*/
public BankAcount( )
CONSTRUCTOR-assign default values
{
balance = 0;
}
/**
* Constructs a bank account with an initial balance.
Document constructor’s purpose
* @param initialBalance the starting balance for account
*/
public BankAcount(double initialBalance)
CONSTRUCTOR-assign user value's
{
balance = initialBalance;
}
//-----------------------------METHODS-----------------------------------------------/**
* Withdraws money from the bank account.
Document the method's purpose
* @param amount amount to withdraw
Document each parameter
*/
public void withdraw(double amount)
METHOD – NO RETURN, 1 PARAMETER
{
balance = balance - amount;
}
/**
* Gets current balance of the bank account.
Document the method's purpose
* @return the current balance
Document the return value
*/
public double getBalance()
METHOD – RETURN, NO PARAMETERS
{
return balance;
}
//-----------------------------INSTANCE VARIABLES------------------------------------private double balance;
}
public class BankAccountTester
Example Tester class for BankAccount
{
public static void main(String[] args)
{
BankAccount account = new BankAccount();
construct BankAccount object
account.deposit(1000);
call deposit
System.out.println("Balance is " + account.getBalance());
display balance
}
}
Java Reference Guide(Chapters 1-7)
Page 7
3/6/2016
Algorithm for Creating a New Program
Read the program
requirements
System Analysis
Create a Class Diagram
DETERMINE METHODS
Accessor -"getter"
Returns data
Return type: double, int, String
Parameters: none
Mutator -"setter"
Changes data
Return type: void
Parameters: usually has some
BankAccount
Start Program in BlueJ
Create project
Create class
- balance:double
+ RATE: double = .07
variableName:type
constantName:type = value
+ getBalance():double
+ deposit(double amount):void
+ withdraw(double amount):void
method(parms):type
- private
+ public
Add necessary import lines
Javadoc comments for class
Create constructors
Default
User defined
Create methods
public BankAccount
{
balance = 0;
}
public BankAccount (double initialBalance)
{
balance = initialBalance;
}
ACCESSORS
public double getBalance()
{
return balance;
}
public String getName()
{
return employeeName;
}
MUTATORS
Add javadoc comments
For constructors, methods
Create instance variables
Class constants
Compile class
Create a Tester Class
Compile Tester class
Test the program
public void deposit()
{
balance = balance + amount;
}
private double balance;
public static final double RATE = .07;
public void addInterest(double rate)
{
double interest = balance * rate/100;
balance = balance + interest;
}
public void setBase(double newBase)
{
base = newBase;
}
public class BankAccountTester
{
public static void main(String[] args)
{
BankAccount account = new BankAccount();
account.deposit(1000);
account.withdraw(400);
System.out.println("Balance = " + account.getBalance());
}
}
JAVADOC COMMENTS (for constructors and methods)
\**
* Description of what code does
* @param parmName what is the parm used for
* @return description of what is being returned
*/
Download