Question

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 two substrings containing hours and

minutes. Convert these substrings to integers and save them into the instance

variables.

4. In the TimeDemo class, add a condition to the loop that converts the user

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

//TASK1

//Time.java

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

//validate hours and minutes are valid values

hours=Integer.parseInt( militaryTime.substring(0,2));


minutes=Integer.parseInt(militaryTime.substring(3,5));


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;

}

}


//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.println(

"Do you want to enter another (Y/N)? ");

response = keyboard.nextLine();

answer = response.charAt(0);

}

}

}



Add a comment
Answer #2

//Task2.java


import java.util.StringTokenizer;

import java.util.Scanner;

import java.io.File;



public class Task2{


public static void main(String args[])

{

String content="";

try {

content = new Scanner(new File("secret.txt")).useDelimiter("\\Z").next();

}

catch(Exception e)

{System.out.println("Cannot find file"); }

StringTokenizer st =new StringTokenizer(content);

StringBuffer sBuffer = new StringBuffer();

int i=4;

while(st.hasMoreTokens() )

{

String t = st.nextToken();

i++;

if( i==5)

{

sBuffer.append(Character.toUpperCase(t.charAt(0)));

i=0;

}

  

}

System.out.println("Secret is: "+sBuffer);

  

  

}

}

Add a comment
Answer #3

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 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 military time." );

}

//Check to make sure there are 5 characters

else if (//CONDITION TO CHECK LENGTH OF STRING)

{

System.out.println(militaryTime +

" is not a valid military time." );

}

else

{

//Check to make sure the colon is in

//the correct spot

if (//CONDITION TO CHECK COLON POSITION)

{

System.out.println(militaryTime +

" is not a valid military time." );

}

else if (//CONDITION TO CHECK FOR DIGIT)

{

System.out.println(militaryTime +

" is not a valid military time." );

}

else if (//CONDITION TO CHECK FOR DIGIT)

{

System.out.println(militaryTime +

" is not a valid military time." );

}

else if (//CONDITION TO CHECK FOR DIGIT)

{

System.out.println(militaryTime +

" is not a valid military time." );

}

else if (//CONDITION TO CHECK FOR DIGIT)

{

System.out.println(militaryTime +

" is not a valid military time." );

}

else

{

//SEPARATE THE STRING INTO THE HOURS

//AND THE MINUTES, CONVERTING THEM TO

//INTEGERS AND STORING INTO THE

//INSTANCE VARIABLES

//validate hours and minutes are valid

//values

if(hours > 23)

{

System.out.println(militaryTime +

" is not a valid military" +

" time." );

}

else if(minutes > 59)

{

System.out.println(militaryTime +

" is not a valid military" +

" 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

Add a comment
Know the answer?
Add Answer to:
Task #1 Character and String Class Methods 1. Copy the files Time.java (code listing 9.1) and...
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
  • 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...

  • Task #3 Arrays of Objects 1. Copy the files Song java (see Code Listing 7.1), Compact...

    Task #3 Arrays of Objects 1. Copy the files Song java (see Code Listing 7.1), Compact Disc.java (see Code Listing 7.2) and Classics.txt (see Code Listing 7.3) from the Student Files or as directed by your instructor. Song.java is complete and will not be edited. Classics.txt is the data file that will be used by Compact Disc.java, the file you will be editing. 2. In Compact Disc.java, there are comments indicating where the missing code is to be placed. Declare...

  • Java Programming Task #2 String.split and the StringBuilder Class 1. Copy the file secret.txt (Code Listing...

    Java Programming Task #2 String.split and the StringBuilder Class 1. Copy the file secret.txt (Code Listing 9.3) from the Student CD or as directed by your instructor. This file is only one line long. It contains 2 sentences. 2. Write a main method that will read the file secret.txt, separate it into word tokens. 3. You should process the tokens by taking the first letter of every fifth word, starting with the first word in the file. Convert these letters...

  • 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...

  • In the first task, you will write a Java program that accepts a string of the...

    In the first task, you will write a Java program that accepts a string of the format specified next and calculate the answer based on the user input. The input string should be of the format dddxxdddxx*, where d represents a digit and x represents any character and asterisk at the end represents that the string can have any number of characters at the end. 1. Prompt the user to enter a string with the specific format (dddxxdddxx*) 2. Read...

  • Write the Java code for the class WordCruncher. Include the following members:

    **IN JAVAAssignment 10.1 [95 points]The WordCruncher classWrite the Java code for the class WordCruncher. Include the following members:A default constructor that sets the instance variable 'word' to the string "default".A parameterized constructor that accepts one String object as a parameter and stores it in the instance variable. The String must consist only of letters: no whitespace, digits, or punctuation. If the String parameter does not consist only of letters, set the instance variable to "default" instead. (This restriction will make...

  • DIRECTIONS FOR THE WHOLE PROJECT BELOW BigInt class The purpose of the BigInt class is to...

    DIRECTIONS FOR THE WHOLE PROJECT BELOW BigInt class The purpose of the BigInt class is to solve the problem using short methods that work together to solve the operations of add, subtract multiply and divide.   A constructor can call a method called setSignAndRemoveItIfItIsThere(). It receives the string that was sent to the constructor and sets a boolean variable positive to true or false and then returns a string without the sign that can then be processed by the constructor to...

  • About Classes and OOP in C++ Part 1 Task 1: Create a class called Person, which...

    About Classes and OOP in C++ Part 1 Task 1: Create a class called Person, which has private data members for name, age, gender, and height. You MUST use this pointer when any of the member functions are using the member variables. Implement a constructor that initializes the strings with an empty string, characters with a null character and the numbers with zero. Create getters and setters for each member variable. Ensure that you identify correctly which member functions should...

  • Here is the UML for the class Contact -fullName : string -phoneNum: string -emailAddress : string...

    Here is the UML for the class Contact -fullName : string -phoneNum: string -emailAddress : string +Contact()                     //default constructor sets all attribute strings to “unknown”; no other constructor +setName(string name) : void +setPhone(string pn) : void +setEmail(string em) : void +getName() : string +getPhone() : string +getEmail() : string +printContact() : void         //print out the name, phone numbers and email address Create New Project Name your project: CIS247_Lab7_YourLastName. For this exercise, you may use a header file or one file...

  • Create a program that performs the following operations: 1. Prompt for and accept a string of...

    Create a program that performs the following operations: 1. Prompt for and accept a string of up to 80 characters from the user. • The memory buffer for this string is created by: buffer: .space 80 #create space for string input The syscall to place input into the buffer looks like: li $v0,8 # code for syscall read_string la $a0, buffer #tell syscall where the buffer is li $a1, 80 # tell syscall how big the buffer is syscall 2....

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
ADVERTISEMENT