s6.pdf We have covered that material; you should read the chapter to reinforce what we did in class.
This material is from s7.pdf
and s8.pdf
for(intit; test; between) { BLOCK } for(Type item: collection) for item in collection: { BLOCK BLOCK }
if(predicate) if predicate: { BLOCK BLOCK } if(predicate) if predicate: { TRUEBLOCK TRIUEBLOCK else: } FALSEBLOCK else { FALSEBLOCK } if(predicate) if predicate: { TRUEBLOCK TRIUEBLOCK elif predicate2: } TRUE2BLOCK else if(predicate2) else: { DEFAULT BLOCK TRUE2BLOCK } else { FALSEBLOCK }
Time to switch
This is the switch-case statement.
public class StandOld
{
public String fruit(char c)
{
String out = "";
switch(c) //chars, integer types, Strings, enums
{
case 'a': case 'A':
out = "apple";
break; //each case MUST end with a break.
case 'b': case 'B':
out = "blueberry";
break;
case 'c': case 'C':
out = "cherry";
break;
case 'd': case 'e':
out = "kumquat";
break;
default:
out = "No fruit with this letter";
}
return out;
}
}
Ternary Operator
predicate? ifTrue: ifFalse
public class Foo
{
public double f(double x)
{
return x < 0? -x:x;
}
}
Python's
def f(x):
return -x if x < 0 else x
Big Integer
This class gives Java a Python-like arbitrary-precision integer type. You will notice some important differences with Python, most of which are fairly cosmetic.
Recursion
Here is a little recursive factorial action.
import java.math.BigInteger;
public class Fact
{
public static BigInteger factorial(int n)
{
if(n < 0)
{
throw new IllegalArgumentException();
}
if(n == 1 || n == 0)
{
return BigInteger.ONE;
}
return BigInteger.valueOf(n).multiply(factorial(n-1));
}
public static void main(String[] args)
{
System.out.println(factorial(1000));
System.out.println(factorial(3));
//System.out.println(factorial(-3));
System.out.println(wabbit(2,3,4,5,6));
}
}
while
and do while
while(predicate) while predicate: { BLOCK BLOCK } do the NAG loop { BLOCK }while(predicate);
Starguments
import java.math.BigInteger;
public class Fact
{
public static BigInteger factorial(int n)
{
if(n < 0)
{
throw new IllegalArgumentException();
}
if(n == 1 || n == 0)
{
return BigInteger.ONE;
}
return BigInteger.valueOf(n).multiply(factorial(n-1));
}
//stargument must be last argument
//no keyword args in Java but you
//do have method name overloading.
public static int wabbit(int... factors)
{
int out = 1;
for(int f: factors) //java thinks factors is an array.
{
out *= f;
}
return out;
}
public static void main(String[] args)
{
System.out.println(factorial(1000));
System.out.println(factorial(3));
//System.out.println(factorial(-3));
System.out.println(wabbit(2,3,4,5,6));
}
}