Solution to
Try It Yourself: characters and strings

  1. // text = String given
    for (int i = 0; i < text.length(); i++) {
    	char c = text.charAt(i);
    	if (!(c >= 'a' && c <= 'z') && 	// if c is not a lower-case letter
    	    !(c >= 'A' && c <= 'Z') &&	// and c is not an upper-case letter
    	    !(c >= '0' && c <= '9'))  	// and c is not a digit,
    		System.out.print(c);    	// print out c
    }
    



  2. // number = String containing only positive digits
    int powOfTen = 10;
    
    // get the ones position and add it to num
    int num = number.charAt(number.length() - 1) - '0';
    
    // working backwards through the string, get the next digit,
    // multiply it by the appropriate power of 10, and add it in to num
    for (int i = number.length() - 2; i >= 0; i--) {
    	num += (number.charAt(i) - '0') * powOfTen;
    	powOfTen *= 10;
    }
    	



  3. // number = String containing only digits
    
    int firstDigit = 0; // position of first digit in the string
    int sign = 1;       // multiply by the sign at the end
    
    // check for + or - at the beginning of the string
    if (number.charAt(0) == '-') {
    	sign = -1;
    	firstDigit = 1;
    }
    else if (number.charAt(0) == '+') {
    	firstDigit = 1;
    }
    
    // calculate number as in question 3
    int num = number.charAt(number.length() - 1) - '0';
    int powOfTen = 10;
    for (int i = number.length() - 2; i >= firstDigit; i--) {
    	num += (number.charAt(i) - '0') * powOfTen;
    	powOfTen *= 10;
    }
     
    num *= sign;  // multiply by the sign
    	



  4. phrase.setCharAt(7, 'd');
    phrase.setCharAt(8, 'o');
    phrase.append("ey");
    phrase.insert(3, 'l');
    	



  5. public class Date {
    	private int month, day, year;  // holds month, day, year for date
    
    	/**
    	 * Creates a Date object with the given month, day, and year.  
    	 * Invalid arguments are replaced with 0.
    	 *
    	 * @param m the month (1 <= m <= 12)
    	 * @param d the day (1 <= d <= 31)
    	 * @param y the year (1000 <= y <= 9999)
    	 **/
    	public Date(int m, int d, int y) {
    		month = m;
    		if (month < 1 || month > 12)
    			month = 0;
    		day = d;
    		if (day < 1 || day > 31)
    			day = 0;
    		year = y;
    		if (year < 1000 || year > 9999)
    			year = 0;
    	}
    
    	/**
    	 * Returns the month.
    	 * @return the month
    	 **/
    	public int getMonth() {
    		return month;
    	}
    
    	/**
    	 * Returns the day.
    	 * @return the day
    	 **/
    	public int getDay() {
    		return day;
    	}
    
    	/**
    	 * Returns the year.
    	 * @return the year
    	 **/
    	public int getYear() {
    		return year;
    	}
    
    	/**
    	 * Returns a String representing the date.
    	 * @return the date in the format: mm/dd/yyyy
    	public String toString() {
    		return (month + "/" + day + "/" + year);
    	}
    }