Java 1. Program Specification This will focus on strengthening your skills with manipulating Strings. The String...

Java

1. Program Specification

This will focus on strengthening your skills with manipulating Strings. The String class provides many useful methods, in which this assignment will give you further practice with. You will read in dates in a variety of different formats, parse the dates, and then print them out in a converted format. The dates will be entered in one line by the user, and they will be separated by the word “and”.

2. Date formats

Your program will parse a line of dates written in three styles: day first, month first, and all-numbers.

Day first: The day of the month is first, followed by the month, followed by the year. The month string must be at least 3 letters long, and can be a mix of upper and lowercase letters. Spaces should separate the three parts. Spaces are not allowed between numbers or month names.

ex: 8 Aug 2015
24 February 1988

Month first: The month is first, followed by the day, a comma, then the year. The month may be fully spelled out or an abbreviation at least 3 letters long and be upper or lower case. A space must separate the month and day, but there may be multiple spaces between the two.

ex: March 15, 1967

Jan 17, 1990

All numbers: Month, day, and year are entered as numbers with dashes between them. There may be many spaces around the dashes or none. Spaces are not allowed between the numbers.

ex: 12-4-2008

1-8-2003

3. Requirements

  •  Your program must read a single line that may contain many dates in many formats separated by the word “and”. It will parse out the dates, and print them all in the correct format. The correct format is day first, a space, followed by the full name of the month with the first letter capitalized, a space, and then the year.

  •  Your program must give an error message if a date is invalid. It should give a specific error message for the following cases:

o A month name or abbreviation is misspelled or too short (less than three characters)
o A day or month number is incorrect. Months must be between 1 and 12. Days must be

valid for the month (ignore leap years)
o A year number is too low or high (1900 to 2019). o There are too many dashes in All Numbers format.

 It is ok if your program crashes when calling Integer.parseInt and the argument is not valid.

4. Implementation

There are some specific requirements for how you write the program.

 Use the below build-in methods
o String class: substring, trim, split, toLowerCase, indexOf, or lasIndexOf o Integer class: parseInt

  •  In the main() method, you must prompt the user to enter the dates, read the line of dates, break the line into separate Strings based on the delimiter (“and”), and for each date print “Date : ”. You must also call the appropriate parser here.

  •  One method for parsing each kind of date. These methods either output an error message or the corresponding standard date string.

o public static void parseDayFirst(String dateStr)
o public static void parseMonthFirst(String dateStr) o public static void parseAllNumbers(String dateStr)

 public static boolean isValidMonthDay(int day, int month)
o returns true if the month and day numbers form a valid day of the year (leap years

excluded)

 public static int monthToNumber(String monthStr)
o Takes a string that should be the name or abbreviation of the month name and returns

the number of the month. It returns zero if the name doesn’t match any month or is too short. This method is provided for you.

 public static boolean isValidMonthAbbr(String month)
Takes a month as a String and returns boolean value. True means the passed in month string represents a valid month string (the length of the trimmed month string is greater than or equals 3, and the month string abbreviation is correctly spelled!!!).

Hint: indexOf along with the provided static String array fullNameMonths declared at

the top of the class may be useful here for.  public static boolean isValidYear(int year)

o returns true if the year is valid (1900 to 2018)

 public static String standardDateString(int day, int month, int year)
o takes a day, month, and year as numbers and returns a String containing the date in the

correct format, Day Month Year. (ex. 13 March 2006)

5. Sample Output

Welcome to the Date Converter!

Enter line of dates:8 Aug 2015 and March 15, 1967 and 12-4-2008 Date 1: 8 August 2015
Date 2: 15 March 1967
Date 3: 4 December 2008

Goodbye!

Welcome to the Date Converter!
Enter line of dates:15 xyz 2000 and
Date 1: ERROR: Invalid month string
Date 2: ERROR: Too many dashes
Date 3: ERROR: Invalid month string
Date 4: ERROR: Invalid month or day number

Goodbye!

Welcome to the Date Converter!
Enter line of dates:
ERROR: Empty input line

Goodbye!

Welcome to the Date Converter!

Enter line of dates:and 2-0-2222 and Jan 13, 1190 and March 12,2222 and 9 Date 1: ERROR: No date entered
Date 2: ERROR: Invalid month or day number
Date 3: ERROR: Invalid Year-too low or hi

Date 4: ERROR: Invalid Year-too low or hi Date 5: 9 September 2018

Goodbye!

2-2-22222-and J 10, 2004 andFeb 45 , 2012

- 9-2018

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

Code Provided

package cs251_HW2;

import java.util.Scanner;

public class DateConversion {

//Static variable you can use throughout this class

//contains the months in shorter form

private static String[] abbrMonths = { "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep",

"oct", "nov", "dec" };

//Another static variable you can use, except these contain the months fully spelled out

private static String[] fullNameMonths = { "january", "february", "march", "april", "may", "june", "july", "august", "september",

"october", "november", "december" };

public static void main(String[] args) {

Scanner stdIn = new Scanner(System.in);

System.out.println("Welcome to the CS251 Date Converter!\n");

System.out.print("Enter line of dates:");

String dateEntries = stdIn.nextLine();

//TODO

System.out.println("\nGoodbye!");

stdIn.close();

}

public static void parseDayFirst(String dateStr) {

//TODO

}

public static void parseMonthFirst(String dateStr) {

//TODO

}

public static void parseAllNumbers(String dateStr) {

//TODO

}

public static boolean isValidMonthDay(int day, int month) {

//TODO

}

public static int monthToNumber(String monthStr) {

String lowerCaseMonthStr = monthStr.toLowerCase().substring(0, 3);

int mNumber = 0;

for(int i = 0; i < abbrMonths.length; i++){

if(abbrMonths[i].equals(lowerCaseMonthStr)){

mNumber = i + 1;

break;

}

}

return mNumber;

}

public static boolean isValidMonthAbbr(String str) {

//TODO

}

public static boolean isValidYear(int year) {

//TODO

}

public static String standardDateString(int d, int m, int y) {

//TODO

}

}

In: Computer Science

Unit 09 Drop Box Assignment ONLY ONE FILE may be turned in for the assignment. If...

Unit 09 Drop Box Assignment
ONLY ONE FILE may be turned in for the assignment. If you make a mistake and need to turn
in your work again, you may do so. I will only grade the latest file you turn in. The older ones
will be ignored. For instruction on How To do assignments and create the file see the "How To
Do Homework" document under the "Start Here" button.
The Assignment
Create a Visual Logic flow chart with four methods. Main method will create an array of 5
elements, then it will call a read method, a sort method and a print method passing the array
to each. The read method will prompt the user to enter 5 numbers that will be stored in the
array. The sort method will sort the array in ascending order (smallest to largest). The print
method will print out the array.
A sample run might look like this:
Please enter a number: 2
Please enter a number: 7
Please enter a number: 1
Please enter a number: 10
Please enter a number: 3
Your numbers are: 1, 2, 3, 7, 10

In: Computer Science

A canister contains butane at a pressure of 760 torr and a temprature of 25C. All...

A canister contains butane at a pressure of 760 torr and a temprature of 25C. All of contents of the canister are allowed to react with excess oxygen to produce carbon dioxide and water.

2 (C4H10) + 13O2 -------> 8CO2+ 10(H2O)

Equation is balanced and butane is completely consumed in the reaction, and 46.5g grams of CO2 are produced. What is the volume, in liters, of the canister that contained the butane??

Answer is 6.46L but can anyone please show work for this question?? I just can't get the right answer or near even near it. Please teach me how to approach this problem. Thank You!

In: Chemistry

How would have the Great Depression Devotion encouraged Americans struggling through the Great Depression?

How would have the Great Depression Devotion encouraged Americans struggling through the Great Depression?

In: Economics

I need to know the following values in the table below. All the info you need...

I need to know the following values in the table below. All the info you need should be listed.

1. Write the balanced equation for the reaction between solid zinc and aqueous hydrochloric acid. Be sure to include physical states.

Zn(s) + 2HCl (aq)

In: Chemistry

create database shop; use shop; create table users(    id int null auto_increment,    firstname varchar(255),...

create database shop;
use shop;

create table users(
   id int null auto_increment,
   firstname varchar(255),
   lastname varchar(255) not null,
   primary key (id)
);

create table products(
id int null auto_increment,
name varchar(255),
price float,
primary key (id)
);

create table orders(
   id_users int not null,
   id_items int not null,
   primary key (id_users,id_items),
   foreign key (id_users) references users(id),
   foreign key (id_items) references items(id)
);

write three SQL queries to answer the following questions

1.- Products in the shop catalog; product name.

2.- List of products in stock (not sold); product name, code, price.

3.- Products sold in the shop; product name, code, price and full name of buyer.


Concepts in practice: Relational Databases, SQL.

In: Computer Science

java declare at least five different types of arrays, one, two and three-dimension.

java

declare at least five different types of arrays, one, two and three-dimension.

In: Computer Science

For this assignment, you will apply what you learned in analyzing a simple Java™ program by...

For this assignment, you will apply what you learned in analyzing a simple Java™ program by writing your own Java™ program. The Java™ program you write should do the following:

  • Organize the code capable of throwing an exception of type ParseException as a tryblock.
  • Include a catch block to handle a ParseException error thown by the try block.
  • Include a hard-coded error that results in a ParseException to prove that the code can catch and handle this type of exception.

Complete this assignment by doing the following:

  1. Download and unzip the linked Week 5 Coding Assignment Zip File.
  2. Add comments to the code by typing your name and the date in the multi-line comment header.
  3. Replace the following lines with Java™ code as directed in the file:
  • LINE 1
  • LINE 2
  1. Replace the value assigned with one of the variables so that the program throws an exception.
  2. Comment each line of code you add to explain what you intend the code to do. Be sure to include a comment for the replacement value you added in Step 4 that causes the program to throw an exception.
  3. Test and modify your Java™ program until it runs without errors and produces the results described above.

/************************************************************************************
* Program: PRG/420 Week 5
* Purpose: Week 5 Coding Assignment
* Programmer: TYPE YOUR NAME HERE
* Class: PRG/420   
* Creation Date: TYPE TODAY'S DATE HERE
*************************************************************************************
* Program Summary:   
*   This program converts a given date to a string.
*    The code includes exception handling for a ParseException.
************************************************************************************/

package prg420week5_codingassignment;

import java.util.*; // wildcard to import all the util. classes
import java.text.*; // wildcard to import all the text classes   

public class PRG420Week5_CodingAssignment {

public static void main(String[] args){

// The getInstance() method returns a Calendar object whose calendar fields have been initialized with the current date and time.
Calendar calendar = Calendar.getInstance(); {

LINE 1. BEGIN THE TRY BLOCK.
  
String str_date="01-Nov-17"; // Declare a string that we will use later to format a date like this: ##-XXX-##
DateFormat formatter; // Declare an object of type DateFormat so that we can call its parse() method later
Date myFormattedDate; // Declare a variable of type Date to hold the formatted date
  
formatter = new SimpleDateFormat("dd-MMM-yy"); // Assign a specific date format to the formatter variable

// The given date is taken as a string that is converted into a date type by using
// the parse() method

myFormattedDate = (Date)formatter.parse(str_date);     // setting up the format
  
System.out.println("The formatted date is " + myFormattedDate);
System.out.println("Today is " +calendar.getTime() );
  


LINE 2. WRITE THE CATCH BLOCK TO CATCH EXCEPTIONS OF TYPE ParseException (TO HANDLE EXCEPTION, SIMPLY PRINT THE EXCEPTION)


  
}
}
}

In: Computer Science

Cane Company manufactures two products called Alpha and Beta that sell for $190 and $155, respectively....

Cane Company manufactures two products called Alpha and Beta that sell for $190 and $155, respectively. Each product uses only one type of raw material that costs $8 per pound. The company has the capacity to annually produce 122,000 units of each product. Its average cost per unit for each product at this level of activity are given below:

Alpha Beta
Direct materials $ 40 $ 24
Direct labor 34 28
Variable manufacturing overhead 21 19
Traceable fixed manufacturing overhead 29 32
Variable selling expenses 26 22
Common fixed expenses 29 24
Total cost per unit $ 179 $ 149

The company considers its traceable fixed manufacturing overhead to be avoidable, whereas its common fixed expenses are unavoidable and have been allocated to products based on sales dollars.

a. Assume that Cane normally produces and sells 74,000 Betas and 94,000 Alphas per year. If Cane discontinues the Beta product line, its sales representatives could increase sales of Alpha by 14,000 units. What is the financial advantage (disadvantage) of discontinuing the Beta product line?

b. Assume that Cane expects to produce and sell 94,000 Alphas during the current year. A supplier has offered to manufacture and deliver 94,000 Alphas to Cane for a price of $136 per unit. What is the financial advantage (disadvantage) of buying 94,000 units from the supplier instead of making those units?

c. Assume that Cane expects to produce and sell 69,000 Alphas during the current year. A supplier has offered to manufacture and deliver 69,000 Alphas to Cane for a price of $136 per unit. What is the financial advantage (disadvantage) of buying 69,000 units from the supplier instead of making those units?

d. How many pounds of raw material are needed to make one unit of each of the two products?

In: Accounting

1. Explain why a transaction may have many cursors. Also, how is it possible that a...

1. Explain why a transaction may have many cursors. Also, how is it possible that a transaction may have more than one cursor on a given table? Support your answer with example.

2. After a DBMS has been selected, what is the DBA’s role in DBMS maintenance?

3. Do you think, splitting a table might improve performance? Why/why not.

In: Computer Science

Python Script: Question: Please edit my script for it to get to the right directory and/or...

Python Script:

Question: Please edit my script for it to get to the right directory and/or folder. How to get the right files in the folder to display under files. I don't want anymore errors. Thanks-

#Program to combine multiple excel file into one master file/spreadsheet

#import library

import os
import pandas as pd
cwd = os.path.abspath(")
files = os.listdir(cwd)

#Combine multiple excel files
#This blocks of code will loop through files in directory/folder and append/merge .xlsx files

df = pd.DataFrame()
for file in files:
   if file.endswith('.xlsx'):
       df = df.append(pd.read_excel(file),ignore_index=True

#Display first 5 rows of data/records
df.head()

#Display total columns and rows
df.shape()

df.to_excel('Output.xlsx')

In: Computer Science

Exercise 1 – Calculating factorial (n!) Design a function calledget_factorial that takes an integer n as...

Exercise 1 – Calculating factorial (n!)

Design a function calledget_factorial that takes an integer n as a parameter, and returns n!.

Note #1: 0! = 1:

Note #2: n! is calculated by the following formula: ?! = ? ∗ (? − 1)! ?? ????h?? ???? ?? ??????? ??: ?! = ? ∗ (? − 1) ∗ (? − 2) ∗ ... ∗ 3 ∗ 2 ∗ 1

Exercise 2 – Counting the number of occurrences a letter is found in a phrase

Design a function called get_occurrences that takes two strings as a parameters, and returns the number of times first string appears in the second string.

For example: get_occurrences("x","anthony") à 0 (there are no x’s in Anthony) get_occurrences("y","anthony") à 1 (there is one y in Anthony) get_occurrences("n","anthony") à 2 (there are two n’s in Anthony)

We require that you use loops in your answer. In addition to using a loop, remember the helpful string operations we learned in lecture:

name = "Anthony”

len(name) -> 7

name[3] -> "h"

Exercise 3 – Counting the number of factors of a value within a given range

Design a function called count_multiples that takes three whole positive numbers as parameters. The first two parameters return a range of values to search; the function should return how many numbers within the range are multiples of the third parameter.

For example: count_multiples(1, 9, 2) -> 4 (as 2 goes into 2, 4, 6, and 8)

count_multiples(1, 8, 2) -> 4 (as 2 goes into 2, 4, 6, and 8)

count_multiples(2, 8, 2) -> 4 (as 2 goes into 2, 4, 6, and 8)

count_multiples(20, 28, 3) -> 3 (as 3 goes into 21, 24, and 27)

count_multiples(107, 255, 7) -> 21 (7 goes into 112, 119, ..., 245, 252)

Hint: As you are solving the problem, try and print out any multiples you find as you search the range of values (given by the first and second parameters).

Exercise 4 – Printing out 10 multiples per row

Design a function called print_ten_multiples that takes an integer as a parameter. The function should print out the first 10 multiples of all numbers from 1 up to the given number.

The values printed should be formatted with "3d". Example: print(format(x, "3d"))

Examples of how the function output should look with this formatting:

print_ten_multiples(3):

1 2 3 4 5 6 7 8 9 10

2 4 6 8 10 12 14 16 18 20

3 6 9 12 15 18 21 24 27 30

print_ten_multiples(11):

1 2 3 4 5 6 7 8 9 10

2 4 6 8101214161820

3 6 912151821242730

4 81216202428323640

5 10 15 20 25 30 35 40 45 50

6 12 18 24 30 36 42 48 54 60

7 14 21 28 35 42 49 56 63 70

8 16 24 32 40 48 56 64 72 80

9 18 27 36 45 54 63 72 81 90

10 20 30 40 50 60 70 80 90 100

11 22 33 44 55 66 77 88 99 110

tests = 0
passed = 0

def main():
   test_get_factorial()
   #test_get_occurrences()
   #test_count_multiples()
   #test_print_ten_multiples()
   print("Test results:", passed, "/", tests)


def test_get_factorial():
   print("testing get_factorial...")
   result = get_factorial(0)
   #TODO: add more tests here


def test_get_occurrences():
   print("testing get_occurrences...")
   result = get_occurrences("x","anthony")
   print_test("testing with x and anthony", result==0)
   #TODO: add more tests here


def test_count_multiples():
   print("testing count_multiples...")
   result = count_multiples(1, 9, 2)
   print_test("testing with 1, 9, 2", result==4)
   #TODO: add more tests here


def test_print_ten_multiples():
   print("testing print_ten_multiples")
   print("\nTesting with 3")
   print_ten_multiples(3) # expects final row to be 3 - 30
   #TODO: add more tests here


# TODO: Complete function design
def get_factorial(n):
   ...

# TODO: Complete function design
def get_occurrences(c, text):
   ...


# TODO: Complete function design
def count_multiples(start, end, n):
   ...

# TODO: Complete function design
def print_ten_multiples(max):
   ...


# (str, bool -> None)
# takes the name or description of a test and whether the
# test produced the expected output (True) or not (False)
# and prints out whether that test passed or failed
# NOTE: You should not have to modify this in any way.
def print_test(test_name, result_correct):
   global tests
   global passed
   tests += 1
   if(result_correct):
       print(test_name + ": passed")
       passed += 1
   else:
       print(test_name + ": failed")

# The following code will call your main function
if __name__ == '__main__':
   main()

In: Computer Science

State two reasons why reviewing past case decisions is important for learning business law. Please respond...

  1. State two reasons why reviewing past case decisions is important for learning business law.

Please respond in a full paragraph and justify your answers with reasoning.

In: Economics

Given a 2 Gbps link with TCP applications A, B, and C. Application A has 32...

Given a 2 Gbps link with TCP applications A, B, and C.

  • Application A has 32 TCP connections to a remote web server
  • Application B has 4 TCP connection to a mail server
  • Application C has 15 TCP connections to a remote web server.

According to TCP "fairness", during times when all connections are transmitting, how much bandwidth should Application C have? (Give answer in Mbps, rounded to one decimal place, without units. So for an answer of 1234,567,890 bps you would enter "1234.6" without the quotes.)

In: Computer Science

For a Normal distribution N (μ, σ), if we know the population standard deviation then we...

  1. For a Normal distribution N (μ, σ), if we know the population standard deviation then we can make an inference about:

  1. Mode

  2. Range

  3. Mean

  4. Median

  1. The Normal Distribution curve of heights of a large population of people indicates that the mean height (μ) of the population is 5 feet 6 inches. The 1 standard deviation (σ) in height variation is 2 inches. The people who have the heights between 5 feet 2 inches and 5 feet 10 inches represent:

    1. the range of +1σ to -1 σ

    2. the range of +2σ to -2 σ

    3. the range of +3σ to -3 σ

  2. The Normal Distribution curve of heights of a large population of people indicates that the mean height (μ) of the population is 5 feet 3 inches. The 1 standard deviation (σ) in height variation is 2 inches. The people who have the heights between 4 feet 11 inches and 5 feet 7 inches represent:

    1. the range of +2σ to -2 σ

    2. the range of +σ to -σ

    3. the range of +3σ to -3 σ

  1. The Normal Distribution curve of heights of a large population of people indicates that the mean height (μ) of the population is 5 feet 5 inches. The 1 standard deviation (σ) in height variation is 2 inches. The people who have the heights between 5 feet 3 inches and 5 feet 7 inches represent:

    1. the range of +2σ to -2 σ

    2. the range of +σ to -σ

    3. the range of +3σ to -3 σ

CENTRAL LIMIT THEOREM (Sampling Distribution)

  1. According to the Central Limit Theorem , as the SRS increases, that is as n INCREASES, the sample mean is

  1. Closer to the population mean µ

  2. Away from the population mean µ

  1. According to the Central Limit Theorem, as the SRS increases, that is as n INCREASES, the sample distribution becomes

  1. Left-skewed distribution

  2. Right-skewed distribution

  3. Normal Distribution

A random survey test was given to 100 students. The average score (mean) x was 75. The standard deviation, σ, was 20. Answer the following questions based on this information. Note: n = 100 and look at PPT on Confidence Interval posted on BB.

  1. The ‘Law of Large Numbers’ states that as no. of observations drawn INCREASES, the observed mean gets closer to the

  1. Standard deviation of the population

  2. Probability of the population

  3. Mean of the population

  1. The standard deviation of a Normal Distribution of IQ of a population of adults is 15. For a simple random size (SRS) of 9 from this population, the standard deviation for the sampling distribution will be:

  1. 15

  2. 15/9

  3. 9

  4. 5

  1. The 95%-confidence interval means that we got these numbers using a method that gives CORRECT results …… of the times.

  1. 68%

  2. 100%

  3. 99.7%

  4. 95%

  1. The 95%-confidence interval means that the MARGIN OF ERROR is only:

  1. 95%

  2. 5%

  3. 68%

  4. 99.7%

  1. The margin of error for a sample of n =1000 will be ……. for a sample of n =50.

  1. Less than

  2. Greater than

  3. Equal to

  1. For a sample size of ‘N’ the degrees of freedom for some statistical tests can be computed from the formula:

  1. N-5

  2. N-2

  3. N-3

  4. N-4

HYPOTHESIS TESTING (Read the chapter and you will find the answers)

  1. A Hypothesis always refers to a …….of population.

  1. Mean

  2. Standard deviation

  1. The hypothesis that “The more beer you drink…the higher your blood alcohol level will be” an example of:

    1. Null Hypothesis

    2. Alternative Hypothesis

  1. The value of α = 0.05 means that we are requiring that data give evidence AGAINST the Null Hypothesis so strong that it would happen ……… of the time.

  1. No more than 95%

  2. No less than 95%

  3. No more than 5%

  4. No less than 50%

In: Math