Question

In: Computer Science

JAVA: (Find yourself in PI) In this assignment you will find a numeric string (if it...

JAVA: (Find yourself in PI)

In this assignment you will find a numeric string (if it exists) within a file containing the first 1 million characters of the decimal expansion of PI. The numeric string in question is a 6 character string representing your birth date. E.g., if your birth date is January 1, 1984, then the string is 010184. The file containing the first 1 million characters of the decimal expansion of PI is named pidigits.txt and is available for download from D2L.

Your code should prompt the user for their birthday and then verify that the string entered by the user is indeed a valid date string. Invalid date strings include the following:

013284 // No month has more than 31 days

022905 // 2005 was not a leap year 150184

// There are only 12 months 093196

// September only has 30 days etc.

Thus, a birth date string is of the form: mmddyy where mm is a two digit string representing the month, dd is a two digit string representing the day and yy is a two digit string representing the year. Once a birth date string has been entered by the user and validated, you will open pidigits.txt and read in a single character at a time using a BufferedReader instance. If a non-digit character such as a space, tab, or blank line is read, discard it. If the character is a digit character, “keep it” until a match/non-match has been established. As you read the characters, if there is a match between the birth date string and the characters read, report this to the user. Your code must find all such matches in the file, report all such matches to the user, report the character position in the file at which a given match begins, report the number of comparisons made in establishing the match, and report the total number of comparisons used in reading the entire file.. The format used for reporting is:

Your birthday 022348 was found at character position 1013664 in pidigits.txt The number of comparisons so far is: 919560 Your birthday 022348 was found at character position 1073634 in pidigits.txt The number of comparisons so far is: 973942 The total number of comparisons made in reading this file is: 1111091 If there are no matches for the birth date string, then your code should simply output the total number of comparisons made in reading the file.

Constraints:

Your must use BufferedReader for all IO. No Scanner instances nor JOptionPanes allowed. Failure to observe this constraint will result in a significant loss of points. Each character in pidigits.txt will be read in exactly once using the read() method of the BufferedReader class.

You must use the version of read() that takes no parameters. You do not need to “back up” and reread characters that have already been read. Failure to observe this constraint will result in a significant loss of points.

You are not allowed to store the characters read in an array or any other kind of container. They are to be stored in char variables only. It should be obvious that you need only 6 such variables for this assignment. Failure to observe this constraint will result in a significant loss of points.

You are not allowed to use any methods from the String class for finding matches. You may and should use the isDigit() method. The isDigit() method is a static method in the Character class. Failure to observe this constraint will result in a significant loss of points. Your code must validate that the birth date string entered by the user is indeed a valid date.

You must do this by passing the string as a parameter to a constructor of some sort of Date class. The Date class can be one that you build from scratch or can be based on one of the Date classes in the Java API (Calendar, GregorianCalendar, etc.). The code in your Date class is allowed to use methods from the String class. Failure to observe this constraint will result in a significant loss of points.

The name of the file containing your main() method must be YourFirstNameYourLastNameIV.java. The name of the file containing your code for your Date class must be BirthDate.java. Failure to observe this constraint will result in a significant loss of points.

Solutions

Expert Solution

package BirthDate;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class BirthDay {

   public static void main(String[] args) {

       boolean isvalidDate = false;
       char[] charArray = null;

       while (!isvalidDate) {

           BufferedReader br = new BufferedReader(new InputStreamReader(
                   System.in));
           System.out.println("Enter the Birthday Date");
           try {
               String str = br.readLine();
               System.out.println(str);
               SimpleDateFormat sdf = new SimpleDateFormat("MMddyyyy");
               sdf.setLenient(false);
               // if not valid, it will throw ParseException
               Date date = sdf.parse(str);
               charArray = str.toCharArray();
               System.out.println(" DATe VALIDATED. yOU HAVE ENTERED \n "
                       + date);
               isvalidDate = true;
           } catch (IOException e) {

               // TODO Auto-generated catch block
               e.printStackTrace();
           } catch (ParseException e) {

               e.printStackTrace();
               // return false;
           }
       }
       File file = new File("pidigits.txt");
       if (!file.exists())
           System.err.println("[ file npot found ]");

       try {
           BirthDay.handleFile(file, Charset.defaultCharset(), charArray);

       } catch (IOException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
       }

   }

   private static void handleFile(File file, Charset encoding,
           char[] birthDateArray) throws IOException {
       try (InputStream in = new FileInputStream(file);
               Reader reader = new InputStreamReader(in, encoding);
               // buffer for efficiency
               Reader buffer = new BufferedReader(reader)) {
           int r;
           int index = 0;
           boolean firstMatch = false, secondMatch = false, thirdmatch = false, fourthMatch = false, fifth = false, sixth = false;
           char[] match = new char[6];
           long position = 0;
           long comparision = 0;
           while ((r = reader.read()) != -1) {
               char ch = (char) r;
               if (Character.isWhitespace(ch) || Character.isSpaceChar(ch)) {
                   comparision = comparision + 1;
                   position = position + 1;
               } else if (Character.isDigit(ch)) {
                   comparision = comparision + 1;
                   if (!firstMatch) {
                       if (ch == birthDateArray[0]) {
                           comparision = comparision + 1;
                           index = index + 1;
                           match[0] = ch;
                           firstMatch = true;
                       }
                   } else if (!secondMatch) {
                       if (ch == birthDateArray[1]) {
                           comparision = comparision + 1;
                           index = index + 1;
                           match[1] = ch;
                           secondMatch = true;
                       } else {
                           firstMatch = false;
                       }
                   } else if (!thirdmatch) {
                       if (ch == birthDateArray[2]) {
                           comparision = comparision + 1;
                           index = index + 1;
                           match[2] = ch;
                           secondMatch = true;
                       } else {
                           firstMatch = false;
                           secondMatch = false;
                       }
                   } else if (!fourthMatch) {
                       if (ch == birthDateArray[3]) {
                           comparision = comparision + 1;
                           index = index + 1;
                           match[3] = ch;
                           secondMatch = true;
                       } else {
                           firstMatch = false;
                           secondMatch = false;
                           thirdmatch = false;
                       }
                   } else if (!fifth) {
                       if (ch == birthDateArray[4]) {
                           comparision = comparision + 1;
                           index = index + 1;
                           match[4] = ch;
                           secondMatch = true;
                       } else {
                           firstMatch = false;
                           secondMatch = false;
                           thirdmatch = false;
                           fourthMatch = false;
                       }
                   } else if (!sixth) {
                       if (ch == birthDateArray[5]) {
                           comparision = comparision + 1;
                           index = index + 1;
                           match[5] = ch;
                           secondMatch = true;
                       } else {
                           firstMatch = false;
                           secondMatch = false;
                           thirdmatch = false;
                           fourthMatch = false;
                       }
                   }
               } else {
                   position = position + 1;
               }
           }
           if (position <= 6) {
               position = 0;
           }
           System.err.print("Your birthday ");
           for(char array : birthDateArray){
               System.err.print(array);
           }
           System.err.print("was found at character position " + position
                   + " in pidigits.txt.");
           System.err.println("The number of comparisons so far is:"
                   + comparision);
       }
   }
}

Note : We have main method to runn the above program. Thanks


Related Solutions

FYIPI (Find yourself in PI) In this assignment you will find a numeric string (if it...
FYIPI (Find yourself in PI) In this assignment you will find a numeric string (if it exists) within a file containing the first 1 million characters of the decimal expansion of PI. The numeric string in question is a 6 character string representing your birth date. E.g., if your birth date is January 1, 1984, then the string is 010184. The file containing the first 1 million characters of the decimal expansion of PI is named pidigits.txt and is available...
CREATE A NEW Java PROGRAM that demonstrates : 1.1 numeric and 1 string exception 2. Create...
CREATE A NEW Java PROGRAM that demonstrates : 1.1 numeric and 1 string exception 2. Create your own user defined exception, COMMENT it well, and add code so that it is thrown.
Assignment Instructions Module 4 Writing Assignment (M1-4) You will soon find yourself fulfilling roles in organizations...
Assignment Instructions Module 4 Writing Assignment (M1-4) You will soon find yourself fulfilling roles in organizations where the ability to think ethically about issues will make you much more valuable to employers. In this activity you will refer to the materials in your text and lectures to respond to the questions. Part A The questions in Part A refer to the material discussed in Module 1 of this course. Respond to the following. Discuss reasons why ethics are an important...
use java recursion find # of times a substring is in a string but it has...
use java recursion find # of times a substring is in a string but it has to be the exact same, no extra letters attached to it and capitalization matters. input is 2 strings, output is an int input: ("Hello it is hello it's me hellos" + "hi hellllloooo hi hello" + "hello", "hello") should output: 3 input: (" Hello it is hello it's me hellos" + "hi hellllloooo hi hello" + "hello", "Hello") should output: 1 input: (" Hello...
In Java For this assignment you will implement two methods, find() and replace() relating to Binary...
In Java For this assignment you will implement two methods, find() and replace() relating to Binary Search Trees. These methods are both to be recursive functions. The signatures for those functions must be: /* This method takes a tree node and a key as an argument and returns the tree node if the key is found and returns null if the key is not found. */ BST find(BST T, char key) /* This method takes a tree node and a...
Java:    Find a pattern that will match any string that is --  at least 6 characters...
Java:    Find a pattern that will match any string that is --  at least 6 characters long, -- and begins with a letter or number (\w) -- and contains at least one non-letter and non-number (\W).
Write a C function str_to_float() that takes a numeric string as input and converts it to...
Write a C function str_to_float() that takes a numeric string as input and converts it to a floating point number. The function should return the floating point number by reference. If the conversion is successful, the function should return 0, and -1 otherwise (e.g. the string does not contain a valid number). The prototype of the function is given below int str_to_float(char * str, float * number);
3. Consider the string:”34456754”. Please find the frequency of each number. With a java program.
3. Consider the string:”34456754”. Please find the frequency of each number. With a java program.
Assignment: Create data file consisting of integer, double or String values. Create unique Java application to...
Assignment: Create data file consisting of integer, double or String values. Create unique Java application to read all data from the file echoing the data to standard output. After all data has been read, display how many data were read. For example, if 10 integers were read, the application should display all 10 integers and at the end of the output, print "10 data values were read" My issue is displaying how many integers were read and how many strings...
Code in Java Change the instructionLabel to ask the user to enter a numeric value into...
Code in Java Change the instructionLabel to ask the user to enter a numeric value into the textField and click the button to convert the entered value from kilometers to miles (1.609344 km = 1 mile). When the actionButton on the form is clicked, ActionWindow should take the value entered in the textField, convert it from kilometers to miles, and display the result in the resultField. import java.awt.Container; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; public class...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT