1. Modify the CharacterInfo class shown in Figure so that the tested character is retrieved from user input. Save the file as InputCharacterInfo.java.

    import java.util.Scanner; public class InputCharacterInfo { public static void main(String[] args) { char aChar; String aString; Scanner keyboard = new Scanner(System.in); System.out.print("Enter a character... "); aString = keyboard.nextLine(); aChar = aString.charAt(0); System.out.println("The character is " + aChar); if(Character.isUpperCase(aChar)) System.out.println(aChar + " is uppercase"); else System.out.println(aChar + " is not uppercase"); if(Character.isLowerCase(aChar)) System.out.println(aChar + " is lowercase"); else System.out.println(aChar + " is not lowercase"); aChar = Character.toLowerCase(aChar); System.out.println("After toLowerCase(), aChar is " + aChar); aChar = Character.toUpperCase(aChar); System.out.println("After toUpperCase(), aChar is " + aChar); if(Character.isLetterOrDigit(aChar)) System.out.println(aChar + " is a letter or digit"); else System.out.println(aChar + " is neither a letter nor a digit"); if(Character.isWhitespace(aChar)) System.out.println(aChar + " is whitespace"); else System.out.println(aChar + " is not whitespace"); } }
  2. Write an application that prompts the user for three first names and concatenates them in every possible two-name combination so that new parents can easily compare them to find the most pleasing baby name. Save the file as BabyNameComparison.java.

    import java.util.*; public class BabyNameComparison { public static void main(String[] args) { String name1, name2, name3; Scanner in = new Scanner(System.in); System.out.print("Enter a name >> "); name1 = in.nextLine(); System.out.print("Enter a second name >> "); name2 = in.nextLine(); System.out.print("Enter a third name >> "); name3 = in.nextLine(); System.out.println("The combinations are:"); System.out.println(name1 + " " + name2); System.out.println(name1 + " " + name3); System.out.println(name2 + " " + name1); System.out.println(name2 + " " + name3); System.out.println(name3 + " " + name1); System.out.println(name3 + " " + name2); } }
    1. Create a program that contains a String that holds your favorite inspirational quote and display the total number of spaces contained in the String. Save the file as CountSpaces.java.

      public class CountSpaces { public static void main(String[] args) { String aString = "The best and most beautiful things in the world " + "cannot be seen or even touched - they must be felt with the heart."; int numSpaces = 0; int stringLength = aString.length(); for(int i = 0; i < stringLength; i++) { char ch = aString.charAt(i); if(ch == ' ') numSpaces++; } System.out.println("The number of spaces is " + numSpaces); } }
    2. Write an application that counts the total number of spaces contained in a quote entered by the user. Save the file as CountSpaces2.java.

      import java.util.*; public class CountSpaces2 { public static void main(String[] args) { String aString; int stringLength; Scanner in = new Scanner(System.in); int numSpaces = 0; System.out.print("Enter an inspirational quote >> "); aString = in.nextLine(); stringLength = aString.length(); for(int i = 0; i < stringLength; i++) { char ch = aString.charAt(i); if(ch == ' ') numSpaces++; } System.out.println("The number of spaces is " + numSpaces); } }
  3. Write an application that prompts the user for a password that contains at least two uppercase letters, at least three lowercase letters, and at least one digit. Continuously reprompt the user until a valid password is entered. Display a message indicating whether the password is valid; if not, display the reason the password is not valid. Save the file as ValidatePassword.java.

    import java.util.*; public class ValidatePassword { public static void main(String[] args) { String aString; int stringLength; final int NUM_UPPER_LETTERS = 2; final int NUM_LOWER_LETTERS = 3; final int NUM_DIGITS = 1; int upperCount = 0; int lowerCount = 0; int digitCount = 0; int letterCount = 0; Scanner in = new Scanner(System.in); int numSpaces = 0; System.out.print("Enter a string >> "); aString = in.nextLine(); stringLength = aString.length(); for(int i = 0; i < stringLength; i++) { char ch = aString.charAt(i); if(Character.isUpperCase(ch)) upperCount++; else if(Character.isLowerCase(ch)) lowerCount++; else if(Character.isDigit(ch)) digitCount++; } if(upperCount >= NUM_UPPER_LETTERS && lowerCount >= NUM_LOWER_LETTERS && digitCount >= NUM_DIGITS) System.out.println("Valid password"); else { System.out.println("The password did not have enough of the following:"); if(upperCount < NUM_UPPER_LETTERS) System.out.println("uppercase letters"); if(lowerCount < NUM_LOWER_LETTERS) System.out.println("lowercase letters"); if(digitCount < NUM_DIGITS) System.out.println("digits"); } } }
  4. Write an application that counts the words in a String entered by a user. Words are separated by any combination of spaces, periods, commas, semicolons, question marks, exclamation points, or dashes. Figure 7-17 shows a typical execution. Save the file as CountWords.java.

    import java.util.*; public class CountWords { public static void main(String[] args) { String str; Scanner in = new Scanner(System.in); char ch; int x; int count = 0; int length; boolean previousCharWasPunc = false; System.out.print("Enter a string >> "); str = in.nextLine(); length = str.length(); for(x = 0; x < length; x++) { ch = str.charAt(x); if(ch == ' ' || ch == '.' || ch == ';' || ch == ',' || ch == '!' || ch == '-') { ++count; if(previousCharWasPunc) --count; previousCharWasPunc = true; } else previousCharWasPunc = false; } if(!previousCharWasPunc) ++count; System.out.println("There are " + count + " words in the string"); } }
    1. Write an application that accepts three Strings from the user and, without regard to case, appropriately displays a message that indicates whether the Strings were entered in alphabetical order. Save the file as Alphabetize.java.

      import java.util.*; public class Alphabetize { public static void main(String[] args) { String str1, str2, str3; Scanner in = new Scanner(System.in); System.out.print("Enter first string >> "); str1 = in.nextLine(); System.out.print("Enter second string >> "); str2 = in.nextLine(); System.out.print("Enter third string >> "); str3 = in.nextLine(); if(str1.toLowerCase().compareTo(str2.toLowerCase()) < 0 && str2.toLowerCase().compareTo(str3.toLowerCase()) < 0) System.out.println("You entered the strings in alphabetical order"); else System.out.println("You did not enter the words in alphabetical order"); } }
    2. Write an application that accepts three Strings from the user and displays them in alphabetical order without regard to case. Save the file as Alphabetize2.java.

      import java.util.*; public class Alphabetize2 { public static void main(String[] args) { String str1, str2, str3; Scanner in = new Scanner(System.in); System.out.print("Enter first string >> "); str1 = in.nextLine(); System.out.print("Enter second string >> "); str2 = in.nextLine(); System.out.print("Enter third string >> "); str3 = in.nextLine(); if(str1.toLowerCase().compareTo(str2.toLowerCase()) < 0) if(str2.toLowerCase().compareTo(str3.toLowerCase()) < 0) System.out.println(str1 + " " + str2 + " " + str3); else if(str3.toLowerCase().compareTo(str1.toLowerCase()) < 0) System.out.println(str3 + " " + str1 + " " + str2); else System.out.println(str1 + " " + str3 + " " + str2); else if(str1.toLowerCase().compareTo(str3.toLowerCase()) < 0) System.out.println(str2 + " " + str1 + " " + str3); else if(str3.toLowerCase().compareTo(str2.toLowerCase()) < 0) System.out.println(str3 + " " + str2 + " " + str1); else System.out.println(str2 + " " + str3 + " " + str1); } }
  5. Three-letter acronyms are common in the business world. For example, in Java you use the IDE (Integrated Development Environment) in the JDK (Java Development Kit) to write programs used by the JVM (Java Virtual Machine) that you might send over a LAN (local area network). Programmers even use the acronym TLA to stand for three-letter acronym. Write a program that allows a user to enter three words, and display the appropriate three-letter acronym in all uppercase letters. If the user enters more than three words, ignore the extra words. Save the file as ThreeLetterAcronym.java.

    import javax.swing.*; public class ThreeLetterAcronym { public static void main(String[] args) { String tla = "", entry; int stringLength; int i; int count = 0; int MAX = 3; char c; entry = JOptionPane.showInputDialog(null, "Please enter three words"); stringLength = entry.length(); tla += Character.toUpperCase(entry.charAt(0)); ++count; for(i = 1; i < stringLength; i++) { if(count < MAX) { if(entry.charAt(i) == ' ') { ++i; c = entry.charAt(i); c = Character.toUpperCase(c); tla += c; ++count; } } } JOptionPane.showMessageDialog(null, "Original phrase was " + entry + "\nThree letter acronym is " + tla); } }
  6. Write an application that accepts a word from a user and converts it to Pig Latin. If a word starts with a consonant, the Pig Latin version removes all consonants from the beginning of the word and places them at the end, followed by ay. For example, cricket becomes icketcray. If a word starts with a vowel, the Pig Latin version is the original word with ay added to the end. For example, apple becomes appleay. If y is the first letter in a word, it is treated as a consonant; otherwise, it is treated as a vowel. For example, young becomes oungyay, but system becomes ystemsay. For this program, assume that the user will enter only a single word consisting of all lowercase letters. Save the file as PigLatin.java.

    import javax.swing.*; public class PigLatin { public static void main(String[] args) { StringBuffer str = new StringBuffer(""); String userEntry; String suffix = ""; char letter; int firstVowel = -1; int x; userEntry = JOptionPane.showInputDialog(null, "Enter a word\n" + "to be converted to Pig Latin"); str.insert(0, userEntry); for(x = 0; x < userEntry.length(); ++x) { letter = userEntry.charAt(x); if(isVowel(letter)) { firstVowel = x; x = userEntry.length(); } else if(x != 0 && letter == 'y') { firstVowel = x; x = userEntry.length(); } } for(x = 0; x < firstVowel; ++x) suffix = suffix + userEntry.charAt(x); suffix = suffix + "ay"; for(x = firstVowel - 1; x >= 0; --x) str.deleteCharAt(x); str.append(suffix); JOptionPane.showMessageDialog(null,"Pig Latin version:\n" + str); } public static boolean isVowel(char c) { boolean isVowel = false; if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') isVowel = true; return isVowel; } }
  7. Write a program that inserts parentheses, a space, and a dash into a string of 10 user-entered numbers to format it as a phone number. For example, 5153458912 becomes (515) 345-8912. If the user does not enter exactly 10 digits, display an error message. Continue to accept user input until the user enters 999. Save the file as PhoneNumberFormat.java.

    import javax.swing.*; public class PhoneNumberFormat { public static void main(String[] args) { String inputString; String newString; final String QUIT = "999"; final int VALID_LENGTH = 10; inputString = JOptionPane.showInputDialog(null, "Enter an area code and phone number" + "\nas a series of 10 digits" + "\nEnter " + QUIT + " to quit"); while(!inputString.equals(QUIT)) { if(inputString.length() != VALID_LENGTH) newString = "invalid"; else { newString = "(" + inputString.substring(0,3) + ") " + inputString.substring(3,6) + "-" + inputString.substring(6, inputString.length()); } inputString = JOptionPane.showInputDialog(null, "The number is " + newString + "\n\nEnter an area code and phone number" + "\nas a series of 10 digits" + "\nand I will display it in a nice format" + "\nEnter " + QUIT + " to quit"); } } }
  8. Write an application that determines whether a phrase entered by the user is a palindrome. A palindrome is a phrase that reads the same backward and forward without regarding capitalization or punctuation. For example, “Dot saw I was Tod”, “Was it a car or a cat I saw?”, and “Madam, I’m Adam” are palindromes. Save the file as Palindrome.java.

    import javax.swing.*; public class Palindrome { public static void main(String[] args) { String phrase; String message; int i, j = 0, midPoint; char first, last; boolean isPalindrome = true; phrase = JOptionPane.showInputDialog(null, "Enter a string"); int stringLength = phrase.length(); midPoint = stringLength / 2; i = stringLength - 1; j = 0; while(j <= midPoint) { first = Character.toLowerCase(phrase.charAt(j)); last = Character.toLowerCase(phrase.charAt(i)); if(first != ' ' && last != ' ') { if(first != last) { isPalindrome = false; j = midPoint; } --i; ++j; } else if(first == ' ') ++j; else --i; } if(isPalindrome) message = "You entered a plaindrome"; else message = "You did not enter a palindrome"; JOptionPane.showMessageDialog(null, message); } }
  9. In Chapter 4, you created a class named Game that included two Team objects that held data about teams participating in a game. Modify the Game class to set the game time to the message Game cancelled! if the two teams in a game do not have the same value for the sport. (In other words, a girls’ basketball team should not have a game scheduled with a boys’ tennis team.) Save the revised class as Game.java. Write a program to demonstrate a valid and an invalid game.

    public class Game { private Team team1; private Team team2; private String time; public Game(Team t1, Team t2, String time) { team1 = t1; team2 = t2; if(t1.getSport().equals(team2.getSport())) this.time = time; else this.time = "Game cancelled!"; } public Team getTeam1() { return team1; } public Team getTeam2() { return team2; } public String getTime() { return time; } }
  10. Create a TaxReturn class with fields that hold a taxpayer’s Social Security number, last name, first name, street address, city, state, zip code, annual income, marital status, and tax liability. Include a constructor that requires arguments that provide values for all the fields other than the tax liability. The constructor calculates the tax liability based on annual income and the percentages in the following table. Marital Status Income ($) Single Married 0–20,000 15% 14% 20,001–50,000 22% 20% 50,001 and over 30% 28% In the TaxReturn class, also include a display method that displays all the TaxReturn data. Save the file as TaxReturn.java. Create an application that prompts a user for the data needed to create a TaxReturn. Continue to prompt the user for data as long as any of the following are true: • The Social Security number is not in the correct format, with digits and dashes in the appropriate positions—for example, 999-99-9999. • The zip code is not five digits. • The marital status does not begin with one of the following: S, s, M, or m. • The annual income is negative. After all the input data is correct, create a TaxReturn object and then display its values. Save the file as PrepareTax.java.
    import javax.swing.*; public class PrepareTax { public static void main(String[] args) { String entry = "", ssn, last, first, address, city, state, zip; char status; int x; double income = 0; boolean isGood = false; while(!isGood) { isGood = true; entry = JOptionPane.showInputDialog(null, "Enter your Social Security number"); if(entry.length() != 11) isGood = false; else { for(x = 0; x < 3; ++x) if(!Character.isDigit(entry.charAt(x))) isGood = false; for(x = 4; x < 6; ++x) if(!Character.isDigit(entry.charAt(x))) isGood = false; for(x = 8; x < entry.length(); ++x) if(!Character.isDigit(entry.charAt(x))) isGood = false; if(!(entry.charAt(3) == '-') || !(entry.charAt(6) == '-')) isGood = false; } } ssn = entry; first = JOptionPane.showInputDialog(null, "Enter your first name"); last = JOptionPane.showInputDialog(null, "Enter your last name"); address = JOptionPane.showInputDialog(null, "Enter your address"); city = JOptionPane.showInputDialog(null, "Enter your city"); state = JOptionPane.showInputDialog(null, "Enter your state"); isGood = false; while(!isGood) { isGood = true; entry = JOptionPane.showInputDialog(null, "Enter your Zip code"); if(entry.length() != 5) isGood = false; else for(x = 0; x < 5; ++x) if(!Character.isDigit(entry.charAt(x))) isGood = false; } zip = entry; isGood = false; while(!isGood) { isGood = true; entry = JOptionPane.showInputDialog(null, "Enter marital status"); if(!(entry.charAt(0) == 's' || entry.charAt(0) == 'S' || entry.charAt(0) == 'm' || entry.charAt(0) == 'M')) isGood = false; } status = entry.charAt(0); isGood = false; while(!isGood) { isGood = true; entry = JOptionPane.showInputDialog(null, "Enter your annnual income"); income = Double.parseDouble(entry); if(income < 0) isGood = false; } TaxReturn taxRet = new TaxReturn(ssn, last, first, address, city, state, zip, income, status); taxRet.display(); } }