Question

Chapter 9 Lab Text Processing and Wrapper Classes Lab Objectives ? Use methods of the Character...

Chapter 9 Lab
Text Processing and Wrapper Classes

Lab Objectives

  • ? Use methods of the Character class and String class to process text

  • ? Be able to use the StringTokenizer and StringBuffer classes

    Introduction

    In this lab we ask the user to enter a time in military time (24 hours). The program will convert and display the equivalent conventional time (12 hour with AM or PM) for each entry if it is a valid military time. An error message will be printed to the console if the entry is not a valid military time.

    Think about how you would convert any military time 00:00 to 23:59 into conventional time. Also think about what would be valid military times. To be a valid time, the data must have a specific form. First, it should have exactly 5 characters. Next, only digits are allowed in the first two and last two positions, and that a colon is always used in the middle position. Next, we need to ensure that we never have over 23 hours or 59 minutes. This will require us to separate the substrings containing the hours and minutes. When converting from military time to conventional time, we only have to worry about times that have hours greater than 12, and we do not need to do anything with the minutes at all. To convert, we will need to subtract 12, and put it back together with the colon and the minutes, and indicate that it is PM. Keep in mind that 00:00 in military time is 12:00 AM (midnight) and 12:00 in military time is 12:00 PM (noon).

    We will need to use a variety of Character class and String class methods to validate the data and separate it in order to process it. We will also use a Character class method to allow the user to continue the program if desired.

    The String Tokenizer class will allow us to process a text file in order to decode a secret message. We will use the first letter of every 5th token read in from a file to reveal the secret message.

    Task #1 Character and String Class Methods

  1. Copy the files Time.java (code listing 9.1) and TimeDemo.java (code listing 9.2) from the StudentCD or as directed by your instructor.

  2. In the Time.java file, add conditions to the decision structure which validates the data. Conditions are needed that will

    1. Check the length of the string

    2. Check the position of the colon

    3. Check that all other characters are digits

48

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Task #1 Character and String Class Methods:

Sample Output:

-------------------------------------------------------------------------------------------------------------------------------------

Complete Program:

// File: Time.java
/**Represents time in hours and minutes using the customary conventions*/
public class Time
{
/**hours in conventional time*/
private int hours;

/**minutes in conventional time*/
private int minutes;

/**true if afternoon time, false if morning time*/
private boolean afternoon;

/**Constructs a cutomary time (12 hours, am or pm) from a military time ##:##
@ param militaryTime time in the military format ##:##*/
public Time(String militaryTime)
{
  //Check to make sure something was entered
  if(militaryTime == null)
  {
   System.out.println("You must enter a valid miliary time.");
  }
  //Check to make sure there are 5 characters
  else if(militaryTime.length() != 5)
  {
   System.out.println(militaryTime + " is not a valid miliary time.");
  }
  else
  {
   //Check to make sure the colon is in the correct spot
   if(militaryTime.charAt(2) != ':')
   {
    System.out.println(militaryTime + " is not a valid miliary time.");
   }
   //Check to make sure all other characters are digits
   else if(!Character.isDigit(militaryTime.charAt(0)))
   {
    System.out.println(militaryTime + " is not a valid miliary time.");
   }
   else if(!Character.isDigit(militaryTime.charAt(1)))
   {
    System.out.println(militaryTime + " is not a valid miliary time.");
   }
   else if(!Character.isDigit(militaryTime.charAt(3)))
   {
    System.out.println(militaryTime + " is not a valid miliary time.");
   }
   else if(!Character.isDigit(militaryTime.charAt(4)))
   {
    System.out.println(militaryTime + " is not a valid miliary time.");
   }
   else
   {
    //SEPARATE THE STRING INTO THE HOURS
    //AND THE MINUTES, CONVERTING THEM TO
    //INTEGERS AND STORING INTO THE
    //INSTANCE VARIABLES
    hours = Integer.parseInt( militaryTime.substring(0, 2));
    minutes = Integer.parseInt(militaryTime.substring(3, 5));
    
    //validate hours and minutes are valid values
    if(hours > 23)
    {
     System.out.println(militaryTime + " is not a valid miliary time.");
    }
    else if(minutes > 59)
    {
     System.out.println(militaryTime + " is not a valid miliary time." );
    }
    //convert military time to conventional time
    //for afternoon times
    else if(hours > 12)
    {
     hours = hours - 12;
     afternoon = true;
     System.out.println(this.toString());
    }
    //account for midnight
    else if(hours == 0)
    {
     hours = 12;
     System.out.println(this.toString());
    }
    //account for noon
    else if(hours == 12)
    {
     afternoon = true;
     System.out.println(this.toString());
    }
    //morning times don't need converting
    else
    {
     System.out.println(this.toString());
    }
   }
  }
}


/**toString method returns a conventional time
* @return a conventional time with am or pm*/
public String toString()
{
  String am_pm;
  String zero = "";
  
  if(afternoon)
   am_pm = "PM";
  else
   am_pm = "AM";
  
  if(minutes < 10)
   zero = "0";
  
  return hours + ":" + zero + minutes + " " + am_pm;
}
}

-------------------------------------------------------------------------------------------

// File: TimeDemo.java
import java.util.Scanner;
public class TimeDemo
{
public static void main (String [] args)
{
  Scanner keyboard = new Scanner(System.in);
  char answer = 'Y';
  
  String enteredTime;
  String response;

  while(Character.toUpperCase(answer)=='Y')
  {
   System.out.print("Enter a miitary time using the ##:## form ");
   enteredTime = keyboard.nextLine();
   
   Time now = new Time(enteredTime);
   
   System.out.print("\nDo you want to enter another (Y/N)? ");
   response = keyboard.nextLine();
   answer = response.charAt(0);
  }
}
}

-------------------------------------------------------------------------------------------------------------------------------------

-------------------------------------------------------------------------------------------------------------------------------------

Task #2 StringTokenizer and StringBuffer classes:

Sample Output:

-------------------------------------------------------------------------------------------------------------------------------------

Complete Program:

// File: SecretFileDemo.java
import java.io.*;
import java.util.*;
public class SecretFileDemo
{
public static void main(String[] args)
{
  try
  {
   Scanner infile = new Scanner(new File("secret.txt"));
   StringBuffer sb = new StringBuffer();
   StringTokenizer tokens;
   
   String line;
   String word;
   char firstChar;
   int count = 0;   
        
   while(infile.hasNextLine())
   {
    line = infile.nextLine();
    
    tokens = new StringTokenizer(line);
    
    while(tokens.hasMoreTokens())
    {
     word = tokens.nextToken();
     count++;
     
     if(count % 5 == 0)
     {
      firstChar = Character.toUpperCase(word.charAt(0));
      
      sb.append(firstChar);
     }
      
    }
   }
   
   System.out.println("Secre word: " + sb);
  }
  catch(FileNotFoundException e)
  {
   System.out.println("Input file is not opened.");
   System.exit(0);
  }
}
}

Add a comment
Know the answer?
Add Answer to:
Chapter 9 Lab Text Processing and Wrapper Classes Lab Objectives ? Use methods of the Character...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Time.cpp: #include "Time.h" #include <iostream> using namespace std; Time::Time(string time) {    hours = 0;   ...

    Time.cpp: #include "Time.h" #include <iostream> using namespace std; Time::Time(string time) {    hours = 0;    minutes = 0;    isAfternoon = false;    //check to make sure there are 5 characters    if (//condition to check if length of string is wrong)    {        cout << "You must enter a valid military time in the format 00:00" << endl;    }    else    {        //check to make sure the colon is in the correct...

  • Task #1 Character and String Class Methods 1. Copy the files Time.java (code listing 9.1) and...

    Task #1 Character and String Class Methods 1. Copy the files Time.java (code listing 9.1) and TimeDemo.java (code listing 9.2) from the StudentCD or as directed by your instructor. 2. In the Time.java file, add conditions to the decision structure which validates the data. Conditions are needed that will a. Check the length of the string b. Check the position of the colon c. Check that all other characters are digits 3. Add lines that will separate the string into...

  • PLEASE I NEED C# Objectives Learn the basics of exception handling. Background Exceptions are essentially unexpected...

    PLEASE I NEED C# Objectives Learn the basics of exception handling. Background Exceptions are essentially unexpected situations. It is difficult to write a program that can handle all possible situations, as we have found out through the many programs we have written. For example, should your program accept accidental input? Does it use the metric system or the empirical system? Do users of your program know which system it uses? In order to deal with all these possibilities, exceptions were...

  • Using loops with the String and Character classes. You can also use the StringBuilder class to...

    Using loops with the String and Character classes. You can also use the StringBuilder class to concatenate all the error messages. Floating point literals can be expressed as digits with one decimal point or using scientific notation. 1 The only valid characters are digits (0 through 9) At most one decimal point. At most one occurrence of the letter 'E' At most two positive or negative signs. examples of valid expressions: 3.14159 -2.54 2.453E3 I 66.3E-5 Write a class definition...

  • need help with this JAVA lab, the starting code for the lab is below. directions: The...

    need help with this JAVA lab, the starting code for the lab is below. directions: The Clock class has fields to store the hours, minutes and meridian (a.m. or p.m.) of the clock. This class also has a method that compares two Clock instances and returns the one that is set to earlier in the day. The blahblahblah class has a method to get the hours, minutes and meridian from the user. Then a main method in that class creates...

  • MUST WRITE IN C++ Objective: Learn how to design classes using abstract classes and inheritance Assignment:...

    MUST WRITE IN C++ Objective: Learn how to design classes using abstract classes and inheritance Assignment: In cryptography, encryption is the process of encoding a message or information in such a way that only authorized parties can access it. In this lab you will write a program to decode a message that has been encrypted using two different encryption algorithms. Detailed specifications: Define an abstract class that will be the base class for other two classes. It should have: A...

  • For this week's lab, you will use two of the classes in the Java Collection Framework:...

    For this week's lab, you will use two of the classes in the Java Collection Framework: HashSet and TreeSet. You will use these classes to implement a spell checker. Set Methods For this lab, you will need to use some of the methods that are defined in the Set interface. Recall that if set is a Set, then the following methods are defined: set.size() -- Returns the number of items in the set. set.add(item) -- Adds the item to the...

  • For this week's lab, you will use two of the classes in the Java Collection Framework:...

    For this week's lab, you will use two of the classes in the Java Collection Framework: HashSet and TreeSet. You will use these classes to implement a spell checker. Set Methods For this lab, you will need to use some of the methods that are defined in the Set interface. Recall that if set is a Set, then the following methods are defined: set.size() -- Returns the number of items in the set. set.add(item) -- Adds the item to the...

  • I need help implementing class string functions, any help would be appreciated, also any comments throughout...

    I need help implementing class string functions, any help would be appreciated, also any comments throughout would also be extremely helpful. Time.cpp file - #include "Time.h" #include <new> #include <string> #include <iostream> // The class name is Time. This defines a class for keeping time in hours, minutes, and AM/PM indicator. // You should create 3 private member variables for this class. An integer variable for the hours, // an integer variable for the minutes, and a char variable for...

  • Intro to Java - Assignment JAVA ASSIGNMENT 13 - Object Methods During Event Handling Assignment 13...

    Intro to Java - Assignment JAVA ASSIGNMENT 13 - Object Methods During Event Handling Assignment 13 Assignment 13 Preparation This assignment will focus on the use of object methods during event handling. Assignment 13 Assignment 13 Submission Follow the directions below to submit Assignment 13: This assignment will be a modification of the Assignment 12 program (see EncryptionApplication11.java below). Replace the use of String concatenation operations in the methods with StringBuilder or StringBuffer objects and their methods. EncryptTextMethods.java ====================== package...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
Active Questions
ADVERTISEMENT