Skip to content
Anthony Christe edited this page Aug 30, 2013 · 2 revisions

Solution to FizzBuzz Bonus

for(int i = 1; i <= 100; i++) {
  if(i % 15 == 0) {
    System.out.println("FizzBuzz");
  } else if(i % 3 == 0) {
    System.out.println("Fizz");
  } else if(i % 5 == 0) {
    System.out.println("Buzz");
  } else {
    System.out.println(i);
  }
}

Conditionals

If statements
  • if/else allows us to make a decision based on a Boolean value
  • if, else if statements can be chained
  • Can be nested (try not to nest more than 3 levels)
if(Boolean expression) {
  // Do something
}
else if(Boolean expression) {
  // Do something else
}
else {
  // Do something different
}
/**
 * Makes a statement depending on the current temperature.
 * @param tempF The current temperature in degrees Fahrenheit.
public void testTemp(int tempF) {
  if(tempF < 50) {
    System.out.println("Buuurrrr,it's cold out");
  }
  else if(tempF < 85) {
    System.out.println("Perfect hiking weather");
  }
  else {
    System.out.println("It's rather hot outside");
  }
}
Switch statements
switch(integer/String value) {
  case value 1:
    statement(s);
    break;
  case value 2:
    statement(s);
    break;
  ...
  default:
    statement(s)
}
/**
 * Returns the month name given the month index.
 * Example adapted from http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html.
 * @param monthIndex Index of the month where 1 returns January and 12 returns December.
 * @return The name of the month at index monthIndex.
 */
public String getMonthString(int monthIndex) {
  String monthString;
  switch (month) {
    case 1:
      monthString = "January";
      break;
    case 2:
      monthString = "February";
      break;
    case 3:  
      monthString = "March";
      break;
    case 4:  
      monthString = "April";
      break;
    case 5:  
      monthString = "May";
      break;
    case 6:  
      monthString = "June";
      break;
    case 7:  
      monthString = "July";
      break;
    case 8:  
      monthString = "August";
      break;
    case 9:  
      monthString = "September";
      break;
    case 10: 
      monthString = "October";
      break;
    case 11: 
      monthString = "November";
      break;
    case 12: 
      monthString = "December";
      break;
    default: 
      monthString = "Invalid month";
      break;
  }
  return monthString;
}

Looping

  • Java provides four different ways of looping
  • for
  • while
  • do-while
  • for-each
for loops
for(initialization; termination; increment) {
  statement(s);
}
// Count from 1 to 100
for(int i = 1; i <= 100; i++) {
  System.out.println(i);
}
// Count even numbers from 1 to 100
for(int i = 2; i <= 100; i += 2) {
  System.out.println(i);
}
// Count odd numbers from 100 - 1
for(int i = 99; i >= 1; i -= 2) {
  System.out.println(i);
} 
// Infinite loop
for(;;) {
  statement(s);
}
while loops
  • Oracle Documentation of while do/while
  • While loops simply test a boolean expression
  • Initialization and incrementing take place elsewhere
  • for loops and while loops are interchangeable
  • for loops are shorthand for while loops
  • Pre-test loop
while(Boolean expression) {
  // statements
}

What's wrong with the following code?

int i = 10;
while(i > 0) {
  System.out.println(i);
}

Notice that the increment (decrement) doesn't happen, giving us an infinite loop. To fix this, we can change the code to look like the following:

int i = 10;
while(i > 0) {
  System.out.println(i);
  i--;
}
do-while loops
  • Post-test loop
  • Works same as while, except body of loop is executed at least once
  • Useful for getting user input
do {
  statement(s);
} while (Boolean expression);
do {
  // Ask for password
} while (password isn't correct);
do {
  // Get menu option
} while (menu option != exit);
// Number guessing game
import java.util.Random;
import java.util.Scanner;
public static int main(String[] args) {
  Random random = new Random();
  Scanner in = new Scanner(System.in);
  int randomNumber = random.nextInt(100);
  int guess;

  do {
    System.out.print("Guess:");
    guess = in.nextInt();
  } while (guess != randomNumber);

  System.out.println("You guessed correctly!");
}

Getting input from the user

  • Java provides many ways of interacting with the user
  • GUIs, command line arguments, Scanner class
java.util.Scanner
  • Scanner API
  • We will be using the Scanner class for the following use cases
  • Retrieving an integer from a user
  • Retrieving a String from a user
  • Reading a text file from disk
  • Watch out for exceptions (never trust your users, code defensively)
  • Pass System.in to the constructor of the Scanner to get input from the keyboard
import java.util.Scanner;

public static void main(String[] args) {
  String stringInput;
  int integerInput;
  Scanner in = new Scanner(System.in);
  
  System.out.print("Enter a String:");
  stringInput = in.nextLine();

  System.out.print("Enter an integer:");
  integerInput = in.nextInt();
}

It's important to take special care of Scanner.nextInt because if we look at the method specification we can see that it throws an InputMismatchException. More on this in a bit.

Arrays

  • Arrays are an indexed collection of primitives or objects of all the same type
  • Index starts at 0
  • Length can be accessed via [array name].length
Initializing an array

Initialize an array of 0's

int[] myNums = new int[10];

Implicitally create the array

int[] myNums = {1, 5, 7, 2};

Use a loop to fill the array

int[] myNums = new int[10];
for(int i = 0; i < myNums.length; i++) {
  myNums[i] = i;
}

// Print each array element if it's even
for(int i = 0; i < myNums.length; i++) {
  if(i % 2 == 0) {
    System.out.println(i);
  }
}
/**
 * Returns an array with the sum of the elements in the arrays passed in.
 * @param a The first array.
 * @param b The second array.
 * @return A new array where the index i is the sum of a[i] + b[i].
public int[] addArrays(int[] a, int[] b) {
  int[] summed = new int[a.length];
  for(int i = 0; i < a.length; i++) {
    summed[i] = a[i] + b[i];
  }
  return summed;
}
Multi-dimensional Arrays
  • Java uses row-column ordering
  • Number of rows can be found with [array name].length
  • Number of columns can be found with [array name][0].length

Modeling Tic-Tac-Toe

char[][] ticTacToe = new char[3][3];

// First fill the board with all empty spots
for(r = 0; r < ticTacToe.length; r++) {
  for(c = 0; c < ticTacToe[0].length; c++) {
    ticTacToe[r][c] = 'E';
  }
}

/**
 * Allows player X or O to update their chosen spot on the board.
 * @param row The row of the board.
 * @param column The column of the board.
 */
public void setPosition(int row, int column, char player) {
  ticTacTow[row][column] = player;
}

How would you implement the following methods?

public boolean isValidMove(int row, int col, char player);
public boolean didPlayerWin(char player);
public void printBoard();

System.arraycopy

public static void arraycopy(Object src,
             int srcPos,
             Object dest,
             int destPos,
             int length)

Example

int odds = {1, 3, 5, 7, 9};
int evens = {2, 4, 6, 8, 10};
int oddsAndEvens = new int[odds.length + evens.length];

System.arraycopy(odds, 0, oddsAndEvens, 0, odds.length);
System.arraycopy(evens, 0, oddsAndEvens, odds.length, evens.length);

System.out.println(Arrays.toString(oddsAndEvens)); // 1, 3, 5, 7, 9, 2, 4, 6, 8, 10

Exception Handling

  • Oracle Exceptions Tutorial
  • Code that could cause a runtime error should be wrapped in a try block
  • When an error occurs in the try block, the corresponding catch block is executed
import java.util.Scanner;

public class Scrap { 
  public static	void main(String[] args) {
    Scanner in = new Scanner(System.in);
    in.nextInt();
  }
}

What happens if you enter a String above?

import java.util.Scanner;

public class Scrap{ 
  public static	void main(String[] args) {
    Scanner in = new Scanner(System.in);
    try {
      in.nextInt();
    }
    catch (InputMismatchException e) {
      System.out.println("The input was not an Integer");
    }
  }
}

Exceptions can also be chained in the following way:

try {
  // Potentially error prone code
} 
catch ([exception type] [exception name]) {
  // Clean up code
} 
catch ([exception type] [exception name]) {
  // Clean up code
} 
catch ([exception type] [exception name]) {
  // Clean up code
} 
finally {
  // Optional option
  // This code is run whether an exception occurs or not
}

More on exceptions in the future.

Methods

  • Oracle Tutorial on methods
  • Methods are callable units of code
  • Methods must be one of private, public, or protected (access modifiers)
  • Methods may be static
  • Must have a specified return type (may be void if method returns nothing)
  • Methods may take 0 or more parameters
public int add(int a, int b) {
  return a + b;
}

public int multiply(int a, int b) {
  return a * b;
}

public void printWeirdMath() {
  int num = add(1, 2) + multiply(add(3, 1), 4) - add(add(0, 1), add(1, 2));
  System.out.println(add(num, -1));
}

Class basics

  • Oracle classes tutorial
  • Classes contain related attributes (variables) and ways to act on those attributes (methods)
Constructors
  • Constructors are used to initialize a class (setup attributes with default values)
  • Constructors do not have a return type and are named after the class
/**
 * A data type which stores a single integer.
 */
public class IntegerBox {
  private int value;
  public IntegerBox(int value) {
    this.value = value;
  }

  public int getValue() {
    return this.value;
  }
}

...

IntegerBox a = new IntegerBox(11);
IntegerBox b = new IntegerBox(15);

toString method

  • The toString method returns a String with (normally) human readable contents
  • Great for debugging
  • toString is automatically called when you try to use System.out.print* on an object
/**
 * A data type which stores a single integer.
 */
public class IntegerBox {
  private int value;
  public IntegerBox(int value) {
    this.value = value;
  }

  public int getValue() {
    return this.value;
  }

  @Override
  public String toString() {
    return "Value: " + this.value;
  }
}

...

IntegerBox a = new IntegerBox(11);
IntegerBox b = new IntegerBox(15);
System.out.println(a); // Value: 11
System.out.println(b); // Value: 15

Clone this wiki locally