171 Java Command Reference
Class Structure:
public class MyClassName
{
// you can define a class variable
here
public static void main( )
{
// your statements will go
here
// your calls to method1
will have the form: method1()
}
public static void
method1( )
{
// your statements will go
here
}
}
Create variables
- create using format: type name (a class can be a type)
- create arrays of a type using type[] arrayname = new type[number]
- primitive or class (boolean, double, char, integer, Strings)
- instance (outside methods) or local (parameter or inside method)
- call instance variables with this. as prefix.
- variables can only have certain identifiers
(no spaces in the name, can't start with a number, no spec characters, etc)
- ex: Scanner xa ; int y ; int x; String y;
Assign values to variables:
- = or use a method that updates
- identify array elements as arrayname[index]
- get length with arrayname.length
- right side resolves to a value that goes into left side variable name
- ex: x = 3; xa = new Scanner(System.in)
Compare values:
- >,<,==,=>, =< for primitive types only
- equals or compareTo method for classes
- && means And ; || means Or. Can use parentheses to show precedence.
- ex: if (a < b && c < d || a <
c) means: if either A is less than C OR ( A is less than B AND C is less than
D ) it will pass the if statement
Decisions
- If ( ) {} else if ( ) {} else {}
- put decisions inside parentheses - resolve to boolean (true or false)
- ex: if (a < b) { x = 1; } else if ( c < d)
{ x = 2; } else {x = 3;}
Loops (Repeat)
- For ( starter ; keep going condition; incrementer){}
- ex: for (int c = 1; c < 10; c++) { x = x
+ c;}
- While (keep going condition) {}
- Be sure the keep going condition can become false somewhere inside
the loop
- Make sure the loop goes at least once
- ex: while ( x < 10) { x = x - 1; a = a + 1;}
- do / while will execute once all the time and then check the condition
before restarting.
- ex: do {x = x -1; a = a + 1; } while (x < 10);
- Sum construct:
- zero out a variable before the loop (double sum = 0:)
- add to that variable inside the loop (sum = sum + whateverYouWantToCount;)
- print the total after the loop (System.out.println(sum);)
- ex: x = 0; for (int c = 1; c < 10; c++)
{ x = x + c;} // and now x has the total of all c's
Make methods:
- public [static] returnType methodname (type var, type
var){ }
- return needed if not returnType void
- static means the method cannot use instance variables (cuts off "this")
- input parameters are considered local variables. If they are arrays or objects,
their address will be passed so the parameter will point to the caller's copy
of the variable.
- constructors are special methods with no return type and methodname the
same as the class name
- ex: public static int getNumber(){ return 3; }
- ex constructor of MyClass: public MyClass (int
number) { this.number = number;}
Use methods
- variable = [class or object identifier].methodname(var, var);
- if void type, do not set equal to a variable
- input parameters must match contract
- input parameters should not be created as they are passed (meaning no (int
x, String y), just (x,y))
- if the method is not static, you cannot call it with [class ], you
must use [object identifier].
- ex: myScanner.nextLine(); anotherMethodinMyClass(6,2);
new Scanner(System.in)
Make classes:
- name instance variables
- encapsulate with private (fence off anyone of another class from ever using
these directly)
- create constructors: public methodname (type var, type
var){ }
- use instance variables as this.variable name
- methods using "this" cannot be static
Use classes
- Scanner, Point, DecimalFormatter, Random, classes you create
- Create instances using constructor:
- classname variable = new classname(var, var);
- ex: Scanner myScanner = new Scanner(System.in);
- Call methods of an instance:
- variable = object identifier.methodname(var, var);
- ex: int x = myScanner.nextInt();
Print to the screen:
- System.out.println ( what you want to output ); // inside parentheses put
"string" and variables separated with +
- System.out.print // does not go to the next line
- System.out.printf (what you want to output, variable names) (This
wont be on the test)
- Can use DecimalFormatter to format inside println and print (Need to read
this, not to create it)
- When printing an object, it will use the object's toString method to format
the object's information
- ex: System.out.println("Hello, my name is " + myName
+ "My number is " + myNumber);
Comments:
- // -> comment line ex: // this is a comment
- /* xxx */ comment between marks
Read from screen:
- Import a scanner
- Create a scanner
- Print out a prompt to screen first
- Use scanner to read using next(), nextLine(), nextInt(), nextDouble()
- ex:
import java.util.Scanner;
Scanner s = new Scanner(System.in);
System.out.println("enter a number");
ex: int value1 = s.nextInt();
Syntax rules
- Every line ends with { or ;
- Only the following that we know end with {: if, else, for, while, method
header, class header
- Inside parentheses, separate with comma only, except for the for statement,
which separates with semi-colon
- Literals inside double quotes
- char inside single quotes
Tracing
- debug: step / step into and see values
- hand tracing: local variables and values inside a class
- follow code that creates objects and calls methods on the objects;
- -----> following them all the way into the class methods
Details on some classes we used:
Scanner: import java.util.*;
create instance: Scanner x = new Scanner(System.in);
call methods: int y = x.next();
Random: import java.util.Random;
create instance: Random x = new Random();
call methods: int y = x.nextInt(6);
Decimal Format: Library: import java.text.DecimalFormat; ---> (we did not
use this much)
Create instance: DecimalFormat percentage2 = new DecimalFormat(0.00%);
Call methods: System.out.println(percentage2.format(.308)); // will print 30.80
0 = required position
# = show it if you have it
% = make it a % (mult by 100)
E = E notation (scientific)
String:
- stringvar.charAt(3) // will be a character
- stringvar.length() // will be an integer
- stringvar.equals(somethingOtherString) // will be either true or false (a
boolean)
- stringvar.toUpperCase() // will be a String that is all uppercase
- stringvar.toLowerCase() // will be a String that is all lowercase
- stringvar.subString(2) // will be a String starting in position 2 to the
end
- stringvar.subString(2, 5) // will be a String starting in position 2 and
ending in position 4
- stringvar.indexOf("xx",2) // return the index of the first place
xx is found, starting the search in position #2.
- Format
- ex: newString = myOriginalString.toLowerCase();
Math:
- absolute value ex: myDoubleVar= Math.abs(#);
- random ex: myDoubleVar = Math.random();
- minimum: Math.min(#,#)
- maximum: Math.max(#,#)
- raise to a power: Math.pow(#,#) : Note: The first number is raised to the
second number
- knows PI and E
Graphics:
Picture It
import picture knowledge: javalib.worldimages.*;
import color knowledge: java.awt.Color;
Make WorldImages using AImage.make<shape> , AImage.makeFromFile
Place images on top of each other using <your world image>.
place (<your other world image> , x,y)
x indicates how far to the right; y indicates how far down (positive)
Show your image with <your world image>.show()