Contents
- ./Birthday.java
- ./FindDuplicates2.java
- ./FindDuplicates3.java
- ./FindDuplicates.java
- ./ListIteratorExamples.java
- ./MapExample.java
./Birthday.java 1/6
[top][prev][next]
import java.util.GregorianCalendar;
/**
* Pedagogical purpose: demonstrates use of throwing
* IllegalArgumentExceptions to prevent errors.
*
* @author CSCI209
*/
public class Birthday {
private int day;
private int month;
private static final int[] DAYS_IN_MONTH = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
private static final String[] MONTHS = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
/**
* Creates a new Birthday object with the given month and day
*
* @param month the integer month of the birthday, e.g., January is 1, February is 2
* @param day the day of the month of the birthday
*/
public Birthday(int month, int day) {
setBirthday(month, day);
}
/**
* Returns a String representation of the Birthday as "month/day"
*
* @return the Birthday as a string in the format "month/day"
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append(month);
builder.append("/");
builder.append(day);
return builder.toString();
}
/**
* Rather than setting the month and the day in separate methods,
* this is a better way to implement setting the month and the day. Why?
*
* @param month the integer month of the birthday, e.g., January is 1, February is 2 (between 1-12)
* @param day the day of the month of the birthday (between 1 and the number of possible days in the month)
* @throws IllegalArgumentException if month or day are invalid
*/
public void setBirthday(int month, int day) {
boolean error = false;
StringBuilder errorMessage = new StringBuilder();
if( month < 1 || month > 12) {
error = true;
errorMessage.append("month must be between 1 and 12");
}
if( day < 1 || day > 31 ) {
if( error ) {
errorMessage.append(" and ");
}
errorMessage.append("day must be between 1 and 31\n");
error = true;
}
// don't need to check if there was a problem with the month
else if( !error && day > DAYS_IN_MONTH[month - 1] ) {
error = true;
errorMessage.append( MONTHS[month-1] + " has only " + DAYS_IN_MONTH[month-1] + " days.");
}
if( error ) {
throw new IllegalArgumentException(errorMessage.toString());
}
// only set the month and day after we know that
// the month and day are valid.
this.month = month;
this.day = day;
}
/**
* Returns the day of the month of the Birthday
* @return the day of the month of the Birthday
*/
public final int getDay() {
return day;
}
/**
* Returns the month of the Birthday, where 1 is January, 2 is February, ...
* @return the month of the Birthday, where 1 is January, 2 is February, ...
*/
public final int getMonth() {
return month;
}
/**
* @param args
*/
public static void main(String[] args) {
Birthday b = new Birthday(1, 1);
System.out.println("New Year's Baby: " + b);
Birthday leapYearBaby = new Birthday(2, 29);
System.out.println("Leap Year Baby: " + leapYearBaby);
b.setBirthday(4, 30); // this should work
System.out.println("End of April birthday: " + b);
/*
Test calling the method with the exceptions:
Each of the statements below, separately, will throw an exception.
Comment out the others to see what one of them does.
(Wouldn't it be great if we had a better way to test exceptions?)
*/
b.setBirthday(1,32);
b.setBirthday(2,30);
b.setBirthday(0, 32);
Birthday b2 = new Birthday(1, 32);
}
}
./FindDuplicates2.java 2/6
[top][prev][next]
import java.util.HashSet;
import java.util.Set;
/**
* From the array of command-line arguments, identify the duplicates.
*
*
*
* @author CSCI209 Class
*
*/
public class FindDuplicates2 {
/**
* @param args
*/
public static void main(String[] args) {
System.out.println("This program finds the duplicates in the command-line arguments.");
Set<String> nonDuplicates = new HashSet<>();
for( String string : args ) {
if( nonDuplicates.contains(string) ) {
System.out.println("found duplicate " + string);
} else{
nonDuplicates.add(string);
}
}
}
}
./FindDuplicates3.java 3/6
[top][prev][next]
import java.util.HashSet;
import java.util.Set;
/**
* From the array of command-line arguments, identify the duplicates.
*
* Solution leverages the add method, which returns a boolean value--
* true if that element was not already in the set (so the element was
* added to the set) or false if it was already in the set.
*
* @author CSCI209 Class
*
*/
public class FindDuplicates3 {
/**
* @param args
*/
public static void main(String[] args) {
System.out.println("This program finds the duplicates in the command-line arguments.");
Set<String> nonDuplicates = new HashSet<>();
for( String string : args ) {
if( ! nonDuplicates.add(string) ) {
System.out.println("found duplicate " + string);
}
}
}
}
./FindDuplicates.java 4/6
[top][prev][next]
import java.util.HashSet;
import java.util.Set;
/**
* From the array of command-line arguments, identify the duplicates
*
* @author CSCI209 Class
*
*/
public class FindDuplicates {
/**
* @param args
*/
public static void main(String[] args) {
System.out.println("This program finds the duplicates in the command-line arguments.");
}
}
./ListIteratorExamples.java 5/6
[top][prev][next]
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.List;
import java.util.Random;
/**
* Examples of using List Iterators
*
* @author CSCI209
*/
public class ListIteratorExamples {
/**
* Condition (we are using this for the items that we want to keep in our
* list).
*
* @param value the value to consider
* @return true if the value is evenly divisible by 2
*/
public static boolean condition(int value) {
return value % 2 == 0;
}
/**
* Display the given list, starting with the header.
*
* @param myList the list to be displayed
* @param header the header to display the list
*/
private static void displayList(List<Integer> myList, String header) {
System.out.println(header);
for (Integer i : myList) {
System.out.println(i);
}
}
public static void main(String[] args) {
Random numberGenerator = new Random();
// set up a list
List<Integer> myList = new ArrayList<>();
for (int i = 0; i < 10; i++) {
myList.add(numberGenerator.nextInt());
}
displayList(myList, "Original List:");
System.out.println();
Iterator<Integer> iter = myList.iterator();
while (iter.hasNext()) {
Integer item = iter.next();
if (!condition(item)) {
// alternatively, could mutate this object, if the object has
// mutator methods available.
// Can't replace this item or remove the item and add in a new
// object.
iter.remove();
}
}
displayList(myList, "Next List:");
ListIterator<Integer> iter2 = myList.listIterator(myList.size());
int counter = myList.size();
while( iter2.hasPrevious() ) {
iter2.previous();
if( counter % 2 == 0 ) {
iter2.add(counter);
}
counter--;
}
System.out.println();
displayList(myList, "Final List:");
}
}
./MapExample.java 6/6
[top][prev][next]
import java.util.HashMap;
import java.util.Map;
/**
* Trivial example of using a map.
* Maps the argument to the length of the argument
*
* @author CSCI209
*
*/
public class MapExample {
/**
* @param args
*/
public static void main(String[] args) {
// State the key's type and the value's type
Map<String, Integer> argToLength = new HashMap<>();
for (String arg : args) {
// if there are duplicate arguments, this will write over that entry in the map.
argToLength.put(arg, arg.length());
}
// display the results
System.out.println("Arguments' Lengths: ");
for( String arg : argToLength.keySet() ) {
System.out.println(arg + " --> " + argToLength.get(arg));
}
// ------- Another Example --------
// count the arguments
Map<String, Integer> argToCount = new HashMap<>();
System.out.println("\n");
for (String arg : args) {
// if there are duplicate arguments, this will write over that entry in the map.
if( argToCount.containsKey(arg) ) {
int oldCount = argToCount.get(arg);
// showing using put and getting the old value back
int oldValue = argToCount.put(arg, oldCount + 1);
System.out.println("The old value for " + arg + " was " + oldValue);
} else {
argToCount.put(arg, 1);
}
}
// display the results
System.out.println("\nArguments' Number of Occurrences: ");
for( String arg : argToLength.keySet() ) {
System.out.println(arg + " --> " + argToCount.get(arg));
}
}
}
Generated by GNU Enscript 1.6.5.90.