01b: Algorithms

ICS211, Fall 2012
Dr. Zach

(switch view)

Recap

A01

Tamarin Reminders

Assignment Policies

Some big words

Some algorithm definitions

Characteristics (of informal definition)

More characteristics (of formal CS definition)

Three levels here

Exercise: How to put on shoes

Algorithm selection

Java Review

Basics II: Loops, exceptions, input, etc

Common Loops

Uncommon Loops

API

Using Objects (eg. Strings)

User Input with Scanner (1/3)

User Input with Scanner (2/3)

Catching Exceptions

int n = ... //try: 2 or 0 or 4
int[] nums = {0, 2, 4, 6};
try {
  int x = 15 / nums[n];
  System.out.println(x);
}catch (ArithmeticException e) {
  System.out.println("Can't divide by 0.");
}finally {
  System.out.println("Done.");
}
System.out.println("Goodbye.");

User Input with Scanner (3/3)

//gets a positive integer from the user
Scanner keybd = new Scanner(System.in);
int input = 0;
while (input <= 0) {
  try {
    System.out.print("Enter a positive integer: ");
    input = keybd.nextInt();
    if (input <= 0) {
      System.out.println("That is not a positive integer.");
    }
  }catch (InputMismatchException e) {
    System.out.println("That is not even an integer!");
    keybd.nextLine();  //important: clears the bad input from the input stream
  }
}
System.out.println("You entered: " + input);

To do before next time...