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
int[] myNums = new int[10];

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

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;
}

System.arraycopy

Exception Handling

Oracle Exceptions Tutorial

Methods

Object basics

Clone this wiki locally