Here are the new tools you need for your Array quiz
Note: This test will be more cummulative than the prior ones (except for graphics).
Arrays:
- Definition and Index Numbering:
- One element (value) per index
- index starts at 0
- You can have more than one dimension, with each dimension starting at 0
- Create array variable type with type[ ] variable_name ; ex: int[ ] x
- For 2 dimensional: type[ ][ ] variable name ex: int[ ][ ]
- Fill with a new array with variable_name = new type[ size ]; ex: x = new int[6]
- For 2 dimensional: Fill with a new array with variable_name = new type[ size ][size]; ex: x = new int[6][2]
- OR fill array with a braced list at the time you create it using type[ ] variable_name = {the comma separated list} ex: int[ ] x = {1,2,3}
- For 2 dimensional: one braced list for each row (the first dimension) separated by commas:
- ex: int[ ][ ] x = {{1,2},{3,4},{5,6}} makes int[3][2], with x[0][0] = 1 and x[2][1] = 6
- OR fill array with another array using type[ ] = a method that returns an array
- ex: String[ ] x = word.split(",");
- Access element with variable_name [ index ]; ex: x[3] = 5; int a = x[3];
- For 2 dimensional: Access element with variable_name [ index ] [ index ]; ex: x[3][2] = 5; int a = x[3][3];
- get length with variable_name.length; ex: int len = x.length;
- For 2 dimensional: Number of the first index (rows) is variable_name .length; ex: x.length;
Number of second index (columns) is variable_name [ index ].length; ex: x[1].length gives number of columns in second row.- iterate through an array's values:
- Use a for loop:
- Start at 0 and end before the array length;
- Access the array variable name [counter]
- For 2 dimensional: I recommend a normal for loop inside of another for loop controlling the values instead
- just to see, not update: for (variable to hold value : name of array) {}
- total array construct: (Same as for any loop)
- Start total bucket at empty (0 or 1);
- accumulate inside loop that iterates through the array with total= total + accumulating value;
- have total at end
Existing Knowledge:
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
}
}
Loops
For loop - repeats when you know the number of times to repeat
for (statement to start the loop; condition that evaluates to true or false; statement to run when the loop repeats)
{
// do something
}What you need to know:
- loop control - know how to set up a loop to run a certain number of times
- scope - variables created in a loop are destroyed at the end of the loop
- only what is in the {} will repeat.
- to accumulate - initialize a variable before the loop, add to itself during the loop, and then print the total at the end of the loop
- tracing - be able to trace all variables in the program including the counter. Know that the first time through the loop it executes the starter statement, and every time follwing it executes the incrementer.) From this you can tell how many times a loop will run.
- inner loop - should not use same counter as outer loop; know what it is, but will not have an inner loop question on the quiz.
FOR coding helps: (but not needed explicitly for the test)
- Don't put a semi-colon at the end of the for condition
- Remember to create the variable used to count the loop with an int statement somewhere in your program. (either in the for statement or before it)
- You can add to the counter between the brackets as well.
- After the first time through, the for loop does the "statement to run when the loop repeats" first, and then checks whether the condition fails.
- When the condition fails, it goes to the bottom bracket of the loop and continues on
- You can have loops inside loops
- Stopping when equal to a single number is dangerous - go with < or > instead when you can.
Work with methods
- Define a method
public static return_type method_name (type parm1, type parm2)
{
...
...
return expression;
}
- add a method right before the class closing curly braces
- a method header is immediately before the method's curly braces
- ex: public static double myMethod(int x){ // your statements go here}
- a method's parameter variables are created inside the parentheses (ex: in the statement above, int x is the parameter creation
- a method's return type is defined before the method name (ex: in the statement above, double is the return type)
- a method with a return type needs to end with a return statement.
- a method with no return type (void) cannot have a return statement
- Class with methods creation step by step guide
- Call a method:
- object_or_class.method_name(parm1, parm2);
- You need the class or object if the method is not in your own class.
- Then, you need the object if the method needs to know some information that is not passed in.
- for static methods you create: <method name> (any parms). ex: myMethod(3);
- for static methods that are not in your class: <class>.<method name> (any parms) ex: Math.pow(5,2);
- for instance methods that are not in your class: <object>.<method name> (any parms) ex: myScanner.nextDouble();
- parameters must match in type and number
- for methods that return a variable: set it = to something. ex: myDoubleVar = myMethod(3);
- Call Math methods (and save their results into variables)
- 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
- Setup to read something from the screen:
- In Java: there are 2 commands needed:
- before the class starts, import the scanner class using: import java.util.Scanner;
- inside the method, create a scanner object using: Scanner kbd = new Scanner(System.in);
- Read something from the screen:
- In Java: <your variable> = < name of the scanner you created above>.nextLine();
- Ask the user for something first, or the system will appear to hang waiting for the user to answer a question you never asked.
- Use the scanner method that matches your variable type.
- example to get the whole line: myStringVar = kbd.nextLine();
- example to get the next word: myStringVar = kbd.next();
- example to get the next double: mydoubleVar = kbd.nextDouble();
- example to get the next int: myIntVar = kbd.nextInt();
- See Sun's page on scanner for much more
- Create boolean expressions:
- use when you want to save the result of a true/false question
- use comparison operator: ==, <,>,<=,>=,!=
- use logical indicator
- OR is ||
- AND is &&
- example: myBooleanVar = x > 5 && x < 10 (x can be between 5 and 10)
- example: myBooleanVar2 = x <5 || x >10 (x can be less than 5 or greater than 10)
If / if else / else
if (condition that evaluates to true or false)
{
// do something
}
else if (condition that evaluates to true or false) // remember that everything that met first criteria doesn't get here
{
// do something else
}
.
. // repeat else if as needed
.
else // remember to put no condition
{
// do something
}If facts:
- else is not needed
- when the condition is met, it executes inside the parentheses and then goes to the end of the if and continues on down
- You can have ifs inside the brackets for another if
Random - Random number generating object
import java.util.Random;
create a new Random Generator : Random myGen = new Random();
Ask your random generator for a new random number: int x = myGen.nextInt(5);
Get a random # starting at 0.While:
While loop - repeats as long as a condition is met
statement to set up so that the first time through the loop it will run
while (test - if it is true, the code in the braces will run)
{
// do something, including changing some variable so the test will be false
}
- loop control - know how to set up the test you want; make the test pass the first time; make the test fail sometime during the loop
- just like a for loop:
- scope - variables created in a loop are destroyed at the end of the loop
- only what is in the {} will repeat.
- to accumulate - initialize a variable before the loop, add to itself during the loop, and then print the total at the end of the loop
- 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);)
- tracing - be able to trace all variables in the program including the counter. Know that the first time through the loop it executes the starter statement, and every time follwing it executes the incrementer.) From this you can tell how many times a loop will run.
do While - repeats, checking the condition after execution of the loop -- will not include on test
- similar to while loop
- always executes once
- checks condition at end of loop instead of beginning
Recursion - a method repeatedly calls itself until some stop condition - winds and unwinds
public static void method(int x)
{
if ( condition to stop ) handle bottom of the winding - where you will stop and turn around
{
// do something that does not call method again
}
else
{
// do something and call method passing it a different x
}
}To create:
- Identify the pattern;
- Identify the end of the pattern (when it should stop repeating), and code that to return a value.
- Code the pattern to call itself, passing a parameter different than what the method was called with.
Graphic - -- will not ask you to write new code for graphic on test
- 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()
Characters:
- Characters are stored by Java as numbers that are then translated on a unicode chart to a letter
Equality Testing
- Doubles are not held exactly, so do not expect two doubles to equal exactly. Let them be off by an absolute difference of .001. (ex: Math.abs(firstVal - secondVal) < .001)
- Strings cannot be compared with == (unless you want to verify the two strings are in the same place in memory). Instead use firstVar.equals(secondVar) == true
Error Handling - Exceptions
- Inside the method that originally finds the problem: Throw an exception with throw new <exception class name>("<a description of the error>")
- The calling method: Catch an error by first trying and then catching any error that occurs:
try
{ call the method and maybe other statements that you only want to execute after a successful method call}
catch (Exception e) // this is any Exception; to catch only a particular type of Exception, use that type
{ statements you want to execute only when the method call threw an error}