Arrays enable the representation of a number of similar items (in terms of their datatypes). They represent these items in an ordered list. Consider the features of arrays and respond to the following: In what programming situations would the use of an array be beneficial? What situations would not warrant the use of an array? Provide an example explaining why? Imagine a programming structure that would deal with these problems. What characteristics should the structure possess? Research the concept of class ArrayList in Java. Describe the advantage of using the ArrayList class over an array. Also discuss in what circumstances you should use one over the other. Please use examples to justify your answers.

Answers

Answer 1

Answer:

Check the explanation

Explanation:

When there is a need to initialize a lot of element of same data types,tht time we use arrays.

We have to use array  whenever it involves simple programs and cases,

dx:saving age of 100 childrans of sametype

When all the ele,ents are of different data type,we hould not use arrays,even when we initialize at runtime,we dont need arrays.i.e when size is not fixed

Linked list can be used instead of arrays

ArrayList:It provides methods for creating, searching, manipulating, and sorting arrays, thereby serving as the base class for all arrays in the common language runtime.

Advantages:

Readymade properties availaible ,so lot of writing and remembering the code can be avoided.

Provide the reference for other arrays

Helps in faster execution


Related Questions

Suppose you design an algorithm to multiply two n-bit integers x and y. The general multiplication technique takes T(n) = O(n2) time. For a more efficient algorithm, you first split each of x and y into their left and right halves, which are n=2 bits long. For example, if x = 100011012, then xL = 10002 and xR = 11012, and x = 24 xL + xR. Then the product of x and y can be re-written as the following: x y = 2n (xL yL) + 2n=2 (xL yR + xR yL) + (xR yR)

Answers

Answer:

See Explaination

Explanation:

a) Assume there are n nits each in x and y.SO we divide them into n/2 and n/2 bits.

x = xL * 2^{n/2} + xR

y = yL * 2^{n/2} + yR

x.y = 2^{n}.(xL.yL) + 2^{n/2}.(xL.yR + xR.yL) +(xR.yR)

If you see there are 4 multiplications of size n/2 and we took all other additions and subtractions as O(n).

So T(n) = 4*T(n/2) + O(n)

Now lets find run time using master theorem.

T(n) = a* T(n/b) + O(n^{d})

a = 4

b = 2

d = 1

if a > b^{d}

T(n) = O(n^v) where v is log a base b

In our case T(n) = O(n^v) v = 2

=> T(n) = O(n^{2})

The splittinng method is not benefecial if we solve by this way as the run time is same even if go by the naive approach

b)

x.y = 2^{n}.(xL.yL) + 2^{n/2}.((xL+xR).(yL+yR)-(xL.yL) - (xR.yR)) +(xR.yR)

Here we are doing only three multipliactions as we changed the term.

So T(n) = 3*T(n/2) + O(n)

a = 3

b = 2

d = 1

if a > b^{d}

T(n) = O(n^v) where v is log a base b

In our case T(n) = O(n^v) v = log 3 base 2

v = 1.584

So T(n) = O(n^{1.584})

As we can see this is better than O(n^{2}).Therefore this algorithm is better than the naive approach.

3.14 LAB: Simple statistics for Python
Given 4 floating-point numbers. Use a string formatting expression with conversion specifiers to output their product and their average as integers (rounded), then as floating-point numbers.

Output each rounded integer using the following:
print('{:.0f}'.format(your_value))

Output each floating-point value with three digits after the decimal point, which can be achieved as follows:
print('{:.3f}'.format(your_value))

Ex: If the input is:

8.3
10.4
5.0
4.8
the output is:

2072 7
2071.680 7.125


So far I came up with the following:
num1 = float(input())
num2 = float(input())
num3 = float(input())
num4 = float(input())

avg = (num1+num2+num3+num4)/4
prod = num1*num2*num3*num4
print('%d %d'%(avg,prod))
print('%0.3f %0.3f'%(avg,prod))

I keep getting this output and I don't know what I'm doing wrong:
7 2071
7.125 2071.680
Expected output should be:
2072 7
2071.680 7.125

Answers

Following are the correct python code to this question:

Program Explanation:

In the python program four variable "n1, n2, n3, and n4" is defined, in which we input method is used that input value from the user end. In this, we use the float method, which converts all the input values into a float value.In the next step, two variables "average and product" are defined, which calculate all input numbers product, average, and hold value in its variable.In the last step, a print method is used, that prints its round and format method value.

Program:

n1 = float(input('Input first number: '))#input first number

n2 = float(input('Input second number: '))#input second number

n3 = float(input('Input third number: '))#input third number

n4 = float(input('Input fourth number: '))#input fourth number

average = (n1+n2+n3+n4)/4 #calculate input number average

product = n1*n2*n3*n4 # calculate input number product

print('product: {:.0f} average: {:.0f}'.format(round(product),round(average))) #print product and average using round function

print('product: {:.3f} average: {:.3f}'.format(product,average)) #print product and average value

Output:

Please find the attachment.

Learn more:

brainly.com/question/14689516

The program calculates the product and average of four floating-point numbers, and outputs them as integers (rounded) and as floating-point numbers with three digits after the decimal point, using specified string formatting expressions.

Here's the Python code to achieve that:

# Input

num1 = float(input())

num2 = float(input())

num3 = float(input())

num4 = float(input())

# Calculate product and average

product = num1 * num2 * num3 * num4

average = (num1 + num2 + num3 + num4) / 4

# Output rounded integers

print('{:.0f} {:.0f}'.format(product, average))

# Output floating-point numbers with three digits after the decimal point

print('{:.3f} {:.3f}'.format(product, average))

User inputs four floating-point numbers.The product and average of the four numbers are calculated.Using string formatting with conversion specifiers, the product and average are output as integers (rounded) and as floating-point numbers with three digits after the decimal point.

This code snippet ensures the desired output format by using the specified string formatting expressions.

Write an algorithm using pseudocode to input numbers . reject any numbers that are negative and count how many numbers are positive . when the number zero is input the process ends and the count of positive numbers is output .​

Answers

Answer:

Explanation:

Let's use Python for this. We will start prompting the user for input number, until it get 0, count only if it's positive:

input_number = Input("Please input an integer")

positive_count = 0

while input_number != 0:

    if input_number > 0:

         positive_count += 1

    input_number = Input("Please input an integer")

print(positive_count)

   

Suppose that the first number of a sequence is x, where x is an integer. Define ; ‍ if is even; ‍ ‍ ‍ if is odd. Then there exists an integer k such that ‍ . Write a program that prompts the user to input the value of x. The program outputs the integer k such that ‍ and the numbers . (For example, if ‍ , then ‍ , and the numbers , respectively, are 75, 226, 113, 340, 170, 85, 256, 128, 64, 32, 16, 8, 4, 2, 1.) Test your program for the following values of x: 75, 111, 678, 732, 873, 2048, and 65535.

Answers

Answer:

The program is written in c++ , go to the explanation part for it, the output can be found in the attached files.

Explanation:

C++ Code:

#include <iostream>

using namespace std;

int main() {

int x;

cout<<"Enter a number: ";

cin>>x;

int largest = x;

int position = 1, count = 0;

while(x != 1)

{

count++;

cout<<x<<" ";

if(x > largest)

{

largest = x;

position = count;

}

if(x%2 == 0)

x = x/2;

else

x = 3*x + 1;

}

cout<<x<<endl;

cout<<"The largest number of the sequence is "<<largest<<endl;

cout<<"The position of the largest number is "<<position<<endl;

return 0;

}

The program prompts the user for an integer ( x ). It calculates ( k ), the number of iterations until ( x ) becomes 1 in a sequence generated by specific rules: if ( x ) is even, it's divided by 2; if odd, it's multiplied by 3 and incremented by 1. .

Here's a Python program that implements the described sequence and finds the integer ( k ) for the given ( x ) value:

```python

def find_k(x):

   k = 0

   while x != 1:

       if x % 2 == 0:

           x = x // 2

       else:

           x = 3 * x + 1

       k += 1

   return k

def generate_sequence(x):

   sequence = [x]

   while x != 1:

       if x % 2 == 0:

           x = x // 2

       else:

           x = 3 * x + 1

       sequence.append(x)

   return sequence

def main():

   test_values = [75, 111, 678, 732, 873, 2048, 65535]

   

   for x in test_values:

       k = find_k(x)

       sequence = generate_sequence(x)

       print(f"For x = {x}, k = {k}, sequence: {sequence}")

if __name__ == "__main__":

   main()

```

This program calculates the integer \( k \) for each given value of \( x \) and generates the sequence according to the rules provided. Then it prints the \( k \) value and the sequence for each test value. You can run this program to verify the results for the provided test values.

Create an application that creates a report from quarterly sales. Console The Sales Report application Region Q1 Q2 Q3 Q4 1 $1,540.00 $2,010.00 $2,450.00 $1,845.00 2 $1,130.00 $1,168.00 $1,847.00 $1,491.00 3 $1,580.00 $2,305.00 $2,710.00 $1,284.00 4 $1,105.00 $4,102.00 $2,391.00 $1,576.00 Sales by region: Region 1: $7,845.00 Region 2: $5,636.00 Region 3: $7,879.00 Region 4: $9,174.00 Sales by quarter: Q1: $5,355.00 Q2: $9,585.00 Q3: $9,398.00 Q4: $6,196.00 Total sales: $30,534.00

Answers

Answer:

See explaination

Explanation:

package miscellaneous;

import java.text.NumberFormat;

import java.util.Currency;

import java.util.Locale;

public class sales {

public static void main(String[] args) {

double[][] sales= {

{1540.0,2010.0,2450.0,1845.0},//region1

{1130.0,1168.0,1847.0,1491.0},//region2

{1580.0,2305.0,2710.0,1284.0},//region3

{1105.0,4102.0,2391.0,1576.0}};//region4

//object for NumberFormat class

//needed in $

NumberFormat defaultFormat = NumberFormat.getCurrencyInstance(java.util.Locale.US);

System.out.println("The sales report application: ");

//the j(th) element in i(th) row in sales matrix contains sales value for

//sales in j(th) quarter

System.out.println("Sales by quarter: ");

System.out.println("Region\tQ1\t\tQ2\t\tQ3\t\tQ4");

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

System.out.print(i+1+"\t");

for(int j=0;j<sales[i].length;j++) {

System.out.print(defaultFormat.format(sales[i][j])+"\t");

}

System.out.println();

}

//i(th) row in the matrix has sales for i(th) region

System.out.println("Sales by region: \n");

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

System.out.print("Region "+(i+1)+":");

double region_sale=0;

for(int j=0;j<sales[i].length;j++) {

region_sale+=sales[i][j];

}

System.out.println(defaultFormat.format(region_sale));

}

System.out.println("\nSales by Quarter: \n");

//we have quarters so for adding up their sales we need 4 variables

double q1=0;

double q2=0;

double q3=0;

double q4=0;

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

for(int j=0;j<sales[i].length;j++) {

//j=0 implies the sales data for first quarter

if(j==0) {

q1+=sales[i][j];

}

//j=1 implies the sales data for second quarter

if(j==1) {

q2+=sales[i][j];

}

//j=2 implies the sales data for third quarter

if(j==2) {

q3+=sales[i][j];

}

//j=3 implies the sales data for fourth quarter

if(j==3) {

q4+=sales[i][j];

}

}

}

System.out.println("Q1: "+defaultFormat.format(q1));

System.out.println("Q2: "+defaultFormat.format(q2));

System.out.println("Q3: "+defaultFormat.format(q3));

System.out.println("Q4: "+defaultFormat.format(q4));

//with the help of 2 loops every sales data

//in the matrix can be accessed, which can be added

//to total_sales variable

double total_sales=0;

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

for(int j=0;j<sales[i].length;j++) {

total_sales+=sales[i][j];

}

}

System.out.println("\nTotal Sales: "+defaultFormat.format(total_sales));

}

}

//Add you starting comment block public class BubbleBubbleStarter //Replace the word Starter with your initials { public static void main (String[] args) { //Task 1: create an input double array list named mylist with some values pSystem.out.println("My list before sorting is: "); //Task 2: print the original list //Use println() to start and then replace with your printList() method after Task 4a is completed. p//Task 3: call the bubblesort method for mylist p//Task 4b: print the sorted list p} //Task 4a: create a method header named printlist to accept a formal parameter of a double array //create a method body to step through each array element println each element p//printList method header p//for loop p//println statement static void bubbleSort(double[] list) { boolean changed = true; do { changed = false; for (int j = 0; j < list.length - 1; j++) if (list[j] > list[j+1]) { //swap list[j] with list[j+1] double temp = list[j]; list[j] = list[j + 1]; list[j + 1] = temp; changed = true; } } while (changed); } }

Answers

Answer:

See explaination

Explanation:

import java.util.Scanner;

public class BubbleBubbleStarter {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

double arr[] = new double[10];

System.out.println("Enter 10 GPA values: ");

for (int i = 0; i < 10; i++)

arr[i] = sc.nextDouble();

sc.close();

System.out.println("My list before sorting is: ");

printlist(arr);

bubbleSort(arr);

System.out.println("My list after sorting is: ");

printlist(arr);

}

static void bubbleSort(double[] list) {

boolean changed = true;

do {

changed = false;

for (int j = 0; j < list.length - 1; j++) {

if (list[j] > list[j + 1]) {

double temp = list[j];

list[j] = list[j + 1];

list[j + 1] = temp;

changed = true;

}

}

} while (changed);

}

static void printlist(double list[]) {

for (int j = 0; j < list.length; j++) {

System.out.println(list[j]);

}

}

}

Complexities of communication are organized into successive layers of protocols: lower-level layers are more specific to medium, higher-level layers are more specific to application. Match the layer name to its functionality: Transport layer Network layer Data link layer Physical layer A. controls transmission of the raw bit stream over the medium B. establishes, maintains and terminates network connections C. ensures the reliability of link D. provides functions to guarantee reliable network link

Answers

Answer:

Transport layer

establishes, maintains and terminates network connections

Network layer

ensures the reliability of link

Data link layer

provides functions to guarantee reliable network link

Physical layer

controls transmission of the raw bit stream over the medium

Explanation:

see Answer

Pfizer increases production of Zithromax® after finding that the number of cases of blinding trachoma is increasing in parts of Africa.

Answers

Answer:

Take Corrective Action

You are working with a MySQL installation in Windows. You plan to use the mysql client utility in batch mode to run a query that has been saved to a file in the C:\mysql_files directory. The name of the file is users.sql, and it includes a command to use the mysql database, which the query targets. You want to save the results of the query to a file named users.txt, which should also be saved to the C:\mysql_files directory. What command should you use to execute the query

Answers

Answer:

mysql -t < c:\mysql_files\users.sql > c:\mysql_files\users.txt

Explanation:

MySQL is a system software that is written in programming language such as c++ and c, the software was initially released on the 23rd day of the month of May, in the year 1995 by Oracle corporation. It is a popular software in companies that are commerce related or orientated since it deals with things related to web database.

So, to answer the question we are given that the file that will results of the query is users.txt and the directory is C:\mysql_files, therefore, the command that should you use to execute the query is; mysql -t < c:\mysql_files\users.sql > c:\mysql_files\users.txt

What are the programming concepts (within or outside the scope of IT210) that you would like to strengthen and delve into further after this course. Why? What is your plan to learn more about the concept(s) you identify? Identify the course concept(s) that you would like this course to provide more content about. Why? Is there any topic and / or concept for which you need more explanation? In addition to Java, what are the programming languages you are interested to learn? Why?

Answers

Answer:

The description for the given question is described in the explanation section below.

Explanation:

I would like to reinforce in advanced or complex concepts such as documents as well as channels, internet programming, multi-threading, after that last lesson.

I am interested in learning web development to develop applications or software. I would also like to explore those concepts by using open source tools.Course concepts will have to develop models for handling.No there is no subject matter or definition you provide further clarity for.I'm interested in studying java as well as web development in comparison to C++ so I can use it in my contract work.

Write a program that reads students’ names followed by their test scores. The program should output each student’s name followed by the test scores and the relevant grade. It should also find and print the highest test score and the name of the students having the highest test score. Student data should be stored in a struct variable of type studentType, which has four components: studentFName and studentLName of type string, testScore of type int (testScore is between 0 and 100), and grade of type char. Suppose that the class has 20 students. Use an array of 20 components of type studentType. Your program must contain at least the following functions: A function to read the students’ data into the array. A function to assign the relevant grade to each student. A function to find the highest test score. A function to print the names of the students having the highest test score. Your program must output each student’s name in this form: last name followed by a comma, followed by a space, followed by the first name; the name must be left justified. Moreover, other than declaring the variables and opening the input and output files, the function main should only be a collection of function calls.

Answers

The program will manage students' test scores using a struct that records each student's name, score, and grade. It involves functions to input data, calculate grades, and identify the highest scorer. Output is formatted as 'LastName, FirstName: Grade'.

Explanation:

Program Structure for Student Grade Records

To create a program for managing student test scores and grades, we would define a struct named studentType with components studentFName, studentLName, testScore, and grade. We'd use an array of studentType of size 20 to store each student's details. The program would include functions to read student data, assign grades, find the highest test score, and print students with the highest score. Grades would be assigned based on the test scores in a typical A-F scale.

The main function should be clean and comprise primarily of function calls to handle various operations such as reading data and processing grades.

The output format for each student's name and grade should be "LastName, FirstName: Grade" with the last name and first name left justified, following the requirements specified for 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.

Answers

Answer:

See explaination

Explanation:

import java.util.Scanner;

public class SortArray {

public static void main(String[] args) {

// TODO Auto-generated method stub

Scanner sc = new Scanner(System.in);

System.out.println("Enter Size Of Array");

int size = sc.nextInt();

int[] arr = new int[size]; // creating array of size

read(arr); // calling read method

sort(arr); // calling sort method

print(arr); // calling print method

}

// method for read array

private static void read(int[] arr) {

Scanner sc = new Scanner(System.in);

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

System.out.println("Enter " + i + "th Position Element");

// read one by one element from console and store in array

arr[i] = sc.nextInt();

}

}

// method for sort array

private static void sort(int[] arr) {

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

for (int j = 0; j < arr.length; j++) {

if (arr[i] < arr[j]) {

// Comparing one element with other if first element is greater than second then

// swap then each other place

int temp = arr[j];

arr[j] = arr[i];

arr[i] = temp;

}

}

}

}

// method for display array

private static void print(int[] arr) {

System.out.print("Your Array are: ");

// display element one by one

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

System.out.print(arr[i] + ",");

}

}

}

See attachment

Design and implement an application that reads a sequence of up to 25 pairs of names and postal (ZIP) codes for individuals. Store the data in an object designed to store a first name (string), last name (string), and postal code (integer). Assume each line of input will contain two strings followed by an integer value, each separated by a tab character. Then, after the input has been read in, print the list in an appropriate format to the screen.

Answers

Answer:

Kindly go to the explanation for the answer.

Explanation:

Person.java

public class Person{

private String firstName, lastName;

private int zip;

public Person(String firstName, String lastName, int zip) {

super();

this.firstName = firstName;

this.lastName = lastName;

this.zip = zip;

}

public String toString() {

String line = "\tFirst Name = " + this.firstName + "\n\tLast Name = " + this.lastName;

line += "\n\tZip Code = " + this.zip + "\n";

return line;

}

}

Test.java

import java.util.ArrayList;

import java.util.Scanner;

public class Test{

public static void main(String args[]) {

Scanner in = new Scanner(System.in);

ArrayList<Person> al = new ArrayList<Person>();

for(int i = 0; i < 25; i++) {

System.out.print("Enter person details: ");

String line = in.nextLine();

String words[] = line.split("\t");

String fname = words[0];

String lname = words[1];

int numb = Integer.parseInt(words[2]);

Person p = new Person(fname, lname, numb);

al.add(p);

}

for(int i = 0; i < 25; i++) {

System.out.println("Person " + (i + 1) + ":");

System.out.println(al.get(i));

}

}

}

Which term describes measurable results expected in a given time frame?

Answers

Answer: I think a deadline?

The term that describes the results expected in a given time frame is the goal. The correct option is A.

What are goals?

The desired states that people want to achieve, maintain, or avoid are referred to as life goals. When we make goals, we commit to imagining, planning for, and obtaining these desired outcomes. The satisfaction with our careers is the satisfaction with our lives because we spend more than half of our waking hours at work.

The most significant professional goal we can set for ourselves is to identify our areas of love and make them into lifelong careers. An objective is something you hope to accomplish. It is the desired outcome that you or a group of people plan for and firmly resolve to attain. The phrase "goal" refers to the outcomes anticipated in a specific time range.

Therefore, the correct option is A, Goals.

To learn more about goals, refer to the link:

https://brainly.com/question/21032773

#SPJ2

The question is incomplete. Your most probably complete question is given below:

Goals

Mind maps

Purposes

Ideas

Implement a Breadth-First Search of the people in the network who are reachable from person id 3980. You can implement BFS with a queue and the pseudocode is given in CLRS. Print out the distance (number of connections) from person 3980 to every person who is reachable from 3980 via edge traversals. Note that not all people in this network may be reachable via edge traversals from user id 3980, so users that are not accessible can be ignored in BFS.

Answers

Answer:

Check the explanation

Explanation:

import java.io.File;

import java.io.FileNotFoundException;

import java.util.LinkedList;

import java.util.Scanner;

import static org.junit.Assert.assertEquals;

/**

* CS146 Assignment 3 Node class This class is used for undirected graphs

* represented as adjacency lists The areFriends() method checks if two people

* are friends by checking if an edge exists between the two

*

*/

public class NetworkAdjList {

   // Initialize array with max number of vertices taken from SNAP

   static int max_num_vertices = 88234;

   static LinkedList<Integer>[] adjacencyList = new LinkedList[max_num_vertices];

   public static void createAdjacencyList() {

       // Initialize array elements

       for (int j = 0; j < max_num_vertices; j++) {

           adjacencyList[j] = new LinkedList<Integer>();

       }

       // Get file path of the 3980.edges file

       String filePath = "C:\\Users\\shahd\\Documents\\CS146\\Assignment 3\\Question 3\\Question3\\src\\a3\\3980.edges";

       File f = new File(filePath);

       // Use Scanner to read edges from the file and put it into adjacency list

       int a;

       int b;

       try {

           Scanner fileIn = new Scanner(f);

           while (fileIn.hasNext()) {

               a = fileIn.nextInt();

               b = fileIn.nextInt();

               adjacencyList[a].add(b);

               adjacencyList[b].add(a); // We need to add the edges both ways

           }

       } catch (FileNotFoundException e) {

           e.printStackTrace();

       }

   }

   public static boolean areFriends(int A, int B) {

       // If the adjacency list contains (A, B) edge, then return true, else false

       if (adjacencyList[A].contains(B)) {

           return true;

       } else {

           return false;

       }

   }

  private static void bfsHelper(boolean visited[], int currentNode, int dis, int sourceNode) {

       dis++;

       if(!visited[currentNode]) {

           visited[currentNode] = true;

           

           for(int neighbor: adjacencyList[currentNode]) {

               System.out.println(neighbor + " is at a distance of " + dis + " from " + sourceNode);

               bfsHelper(visited, neighbor, dis++, sourceNode);

           }

       }

   }

   public static void BFStraversal(int start) {

       boolean visited[] = new boolean[max_num_vertices];

       bfsHelper(visited, start, 0, start);

   }

   public static void main(String[] args) {

       /**

        * These test cases assume the file 3980.edges was used

        */

       createAdjacencyList();

       System.out.println("Testing...");

       assertEquals(areFriends(4038, 4014), true);

       System.out.println("1 of 7");

       System.out.println("Testing...");

       assertEquals(areFriends(3982, 4037), true);

       System.out.println("2 of 7");

       System.out.println("Testing...");

       assertEquals(areFriends(4030, 4017), true);

       System.out.println("3 of 7");

       System.out.println("Testing...");

       assertEquals(areFriends(4030, 1), false);

       System.out.println("4 of 7");

       System.out.println("Testing...");

       assertEquals(areFriends(1, 4030), false);

       System.out.println("5 of 7");

       System.out.println("Testing...");

       assertEquals(areFriends(4003, 3980), true);

       System.out.println("6 of 7");

       System.out.println("Testing...");

       assertEquals(areFriends(3985, 4038), false);

       System.out.println("7 of 7");

       System.out.println("Success!");

   }

}

**************************************************

The Phonebook class must also have the following functions: Constructor with 1 integer parameter for size (numberOfContacts is initially set to 0; allocate memory for myContacts). Copy constructor. Assignment operator. Destructor. int getNumberOfContacts() // Getter int getSize() // Getter contact getContact(int i) //returns contact at index i (you can assume 0 < i < numberOfContacts) bool addContact(string name, string phonenumber, string email) // add a new contact at the end of the phonebook using the received parameters. Returns true if succesful, false if the contact couldn't be added because the phonebook is already full.

Answers

Answer:

See explaination

Explanation:

#include <iostream>

using namespace std;

struct contact

{

string name;

string phoneNumber;

string email;

bool available;

};

class Phonebook

{

private :

int numberOfContacts;

int size;

contact *myContacts;

public :

Phonebook(int size)

{

this->size=size;

this->numberOfContacts=0;

myContacts=new contact[size];

}

~Phonebook()

{

delete[] myContacts;

}

int getNumberOfContacts()

{

return numberOfContacts;

}

int getSize()

{

return size;

}

void addContact(string name,string phonenumber,string email)

{

contact c;

c.name=name;

c.phoneNumber=phonenumber;

c.email=email;

c.available=true;

myContacts[numberOfContacts]=c;

numberOfContacts++;

}

void removeContact(string name)

{

for(int i=0;i<numberOfContacts;i++)

{

if(myContacts[i].name.compare(name)==0)

{

this->myContacts[i].available=false;

contact temp=myContacts[numberOfContacts-1];

myContacts[numberOfContacts-1]=myContacts[i];

myContacts[i]=temp;

numberOfContacts--;

}

}

}

Phonebook(const Phonebook& pb)

{

this->myContacts=pb.myContacts;

this->size=pb.size;

this->numberOfContacts=numberOfContacts;

}

Phonebook& operator=(const Phonebook & pb)

{

myContacts=new contact[size];

this->size=pb.size;

this->numberOfContacts=pb.numberOfContacts;

for(int i=0;i<numberOfContacts;i++)

{

this->myContacts[i]=pb.myContacts[i];

}

return *this;

}

void print()

{

for(int i=0;i<numberOfContacts;i++)

{

if(myContacts[i].available==true)

{

cout<<"Name :"<<myContacts[i].name<<endl;

cout<<"Phone Number :"<<myContacts[i].phoneNumber<<endl;

cout<<"Email :"<<myContacts[i].email<<endl;

cout<<endl;

}

}

}

};

int main(){

Phonebook pb1(10);

pb1.addContact("Williams","9845566778","williamatmail.com");

pb1.addContact("James","9856655445","jamesatmail.com");

cout<<"_____ Displaying Phonebook#1 contacts _____"<<endl;

pb1.print();

pb1.removeContact("Williams");

cout<<"_____ After removing a contact Displaying Phonebook#1 _____"<<endl;

pb1.print();

Phonebook pb2(5);

pb2.addContact("Billy","9845554444","billyatmail.com");

pb2.addContact("Jimmy","9834444444","jimmyatmail.com");

cout<<"_____ Displaying Phonebook#2 contacts _____"<<endl;

pb2.print();

pb2=pb1;

cout<<"____ After Assignment Operator Displaying Phonebook#2 contacts____"<<endl;

pb2.print();

return 0;

}

Nb: Replace the at with at symbol.

Write a Java class to perform the following: 1. Write a method to search the following array using a linear search, ( target elements: 11, 55, 17.). (count the number of comparisons needed). {06, 02, 04, 07, 11, 09, 50, 62, 43, 32, 13, 75, 01, 46, 88, 17} 2. Write a method to sort the array using Selection Sort. (count the number of comparisons needed) 3, Write a method to sort the array using Bubble Sort. (count the number of comparisons needed) 4, Search he sorted array using a binary search (recursive) for the same set of target elements. (count the number of comparisons needed)

Answers

Answer:

Check the explanation

Explanation:

Linear search in JAVA:-

import java.util.Scanner;

class linearsearch

{

  public static void main(String args[])

  {

     int count, number, item, arr[];

     

     Scanner console = new Scanner(System.in);

     System.out.println("Enter numbers:");

     number = console.nextInt();

   

     arr = new int[number];

     System.out.println("Enter " + number + " ");

     

     for (count = 0; count < number; count++)

       arr[count] = console.nextInt();

     System.out.println("Enter search value:");

     item = console.nextInt();

     for (count = 0; count < number; count++)

     {

        if (arr[count] == item)

        {

          System.out.println(item+" present at "+(count+1));

         

          break;

        }

     }

     if (count == number)

       System.out.println(item + " doesn't found in array.");

  }

}

Kindly check the first attached image below for the code output.

Selection Sort in JAVA:-

public class selectionsort {

   public static void selectionsort(int[] array){

       for (int i = 0; i < array.length - 1; i++)

       {

           int ind = i;

           for (int j = i + 1; j < array.length; j++){

               if (array[j] < array[ind]){

                   ind = j;

               }

           }

           int smaller_number = array[ind];  

           array[ind] = array[i];

           array[i] = smaller_number;

       }

   }

     

   public static void main(String a[]){

       int[] arr = {9,94,4,2,43,18,32,12};

       System.out.println("Before Selection Sort");

       for(int i:arr){

           System.out.print(i+" ");

       }

       System.out.println();

         

       selectionsort(arr);

       

       System.out.println("After Selection Sort");

       for(int i:arr){

           System.out.print(i+" ");

       }

   }

}  

Kindly check the second attached image below for the code output.

Bubble Sort in JAVA:-

public class bubblesort {

   static void bubblesort(int[] array) {

       int num = array.length;

       int temp = 0;

        for(int i=0; i < num; i++){

                for(int j=1; j < (num-i); j++){

                         if(array[j-1] > array[j]){

                           

                                temp = array[j-1];

                                array[j-1] = array[j];

                                array[j] = temp;

                        }

                         

                }

        }

   }

   public static void main(String[] args) {

               int arr1[] ={3333,60,25,32,55,620,85};

               

               System.out.println("Before Bubble Sort");

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

                       System.out.print(arr1[i] + " ");

               }

               System.out.println();

                 

               bubblesort(arr1);

               

               System.out.println("After Bubble Sort");

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

                       System.out.print(arr1[i] + " ");

               }

 

       }

}  

Kindly check the third attached image below for the code output.

Binary search in JAVA:-

public class binarysearch {

  public int binarySearch(int[] array, int x) {

     return binarySearch(array, x, 0, array.length - 1);

  }

  private int binarySearch(int[ ] arr, int x,

        int lw, int hg) {

     if (lw > hg) return -1;

     int middle = (lw + hg)/2;

     if (arr[middle] == x) return middle;

     else if (arr[middle] < x)

        return binarySearch(arr, x, middle+1, hg);

     else

        return binarySearch(arr, x, lw, middle-1);

  }

  public static void main(String[] args) {

     binarysearch obj = new binarysearch();

     int[] ar =

       { 22, 18,12,14,36,59,74,98,41,23,

        34,50,45,49,31,53,74,56,57,80,

        61,68,37,12,58,79,904,56,99};

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

        System.out.print(obj.binarySearch(ar,

           ar[i]) + " ");

     System.out.println();

     System.out.print(obj.binarySearch(ar,19) +" ");

     System.out.print(obj.binarySearch(ar,25)+" ");

     System.out.print(obj.binarySearch(ar,82)+" ");

     System.out.print(obj.binarySearch(ar,19)+" ");

     System.out.println();

  }

}

Kindly check the fourth attached image below for the code output

Develop a crawler that collects the email addresses in the visited web pages. You can write a function emails() that takes a document (as a string) as input and returns the set of email addresses (i.e., strings) appearing in it. You should use a regular expression to find the email addresses in the document.

Answers

Answer:

see explaination

Explanation:

import re

def emails(document):

"""

function to find email in given doc using regex

:param document:

:return: set of emails

"""

# regex for matching emails

pattern = r'[\w\.-]+at[\w\.-]+\.\w+'

# finding all emails

emails_in_doc = re.findall(pattern, document)

# returning set of emails

return set(emails_in_doc)

# Testing the above function

print(emails('random text ertatxyz.com yu\npopatxyz.com random another'))

Where can we buy a cryptocurrency? from below options

A) Through a private transaction

B) All the options

C) Cryptocurrency Exchanges

D) In a smart contract

Answers

it would be C

hope this helps!

Define a function drawCircle.

This function should expect a Turtle object, the coordinates of the circle's center point, and the circle's radius as arguments.The function should draw the specified circle. The pen color should be changed to yellow before drawing a circle and the width of the pen to 5 pixels. The algorithm should draw the circle's circumference by turning 3 degrees and moving a given distance 120 times. Calculate the distance moved with the formula 2.0*n*radius/120.0.

Fill in the circle with blue color. After drawing the circle, hide the turtle.

import turtle

import math

def drawCircle(centerpoint, radius):

degree = 3

count = 0

centerpoint = (2.0 * math.pi * radius / 120)

t.home()

t.setheading(degree)

while count <= 120:

t.down()

t.forward(2.0 * math.pi * radius / 120)

t.up()

degree += 3

t.setheading(degree)

count += 1

drawCircle(centerpoint, radius)

Answers

Final answer:

To draw a circle using a Turtle object in Python, you can define a function called drawCircle that takes in the Turtle object, the center point coordinates, and the radius as arguments. This code uses the turtle module in Python to draw a circle.

Explanation:

Draw a Circle using a Turtle in Python

To draw a circle using a Turtle object in Python, you can define a function called drawCircle that takes in the Turtle object, the center point coordinates, and the radius as arguments. Here's an example of how the function can be implemented:

import turtle
import math

def drawCircle(t, centerpoint, radius):
   t.pensize(5)
   t.color('yellow')
   circumference_distance = 2.0 * math.pi * radius / 120.0
   angle = 3
   t.penup()
   t.goto(centerpoint)
   t.pendown()
   for _ in range(120):
       t.forward(circumference_distance)
       t.right(angle)
   t.fillcolor('blue')
   t.begin_fill()
   t.circle(radius)
   t.end_fill()
   t.hideturtle()
t = turtle.Turtle()
drawCircle(t, (0, 0), 100)

This code uses the turtle module in Python to draw a circle. It sets the pen size to 5 pixels and the color to yellow. The circle is drawn by turning 3 degrees and moving a distance of 2.0 * math.pi * radius / 120.0. After drawing the circumference, the function fills the circle with a blue color and hides the turtle.

Final answer:

The drawCircle function is designed for the Python Turtle library to draw a colored circle based on specified parameters. The Turtle's pen is set to yellow and the pen width to 5 pixels before the circle is drawn and filled with blue. After drawing, the Turtle is hidden.

Explanation:

The function drawCircle is intended to work with the Python Turtle graphics library to draw a circle on the screen. The function will expect a Turtle object, the coordinates of the circle's center point, and the circle's radius as arguments. Below is a corrected version of the function that follows the stated requirements:

import turtle
import math

def drawCircle(t, x, y, radius):
   t.penup()
   t.goto(x, y-radius) # Move to the circle's starting point
   t.setheading(0) # Face east
   t.pendown()
   t.color('yellow')
   t.width(5)
   t.begin_fill()
   t.fillcolor('blue')

   for _ in range(120):
       t.forward(2.0 * math.pi * radius / 120.0)
       t.left(3)

   t.end_fill()
   t.hideturtle()

Make sure to create a Turtle object and pass it to the drawCircle function along with the center point's coordinates and the radius of the circle you wish to draw.

Write a function called find_max that takes in a single parameter called random_list, which should be a list. This function will find the maximum (max) value of the input list, and return it. This function will assume the list is composed of only positive numbers. To find the max, within the function, use a variable called list_max that you initialize to value 0. Then use a for loop to loop through random_list. Inside the list, use a conditional to check if the current value is larger than list_max, and if so, re-assign list_max to store this new value. After the loop, return list_max, which should now store the maximum value from within the input list.

Answers

Answer:

see explaination

Explanation:

python code

def find_max(random_list):

list_max=0

for num in random_list:

if num > list_max:

list_max=num

return list_max

print(find_max([1,45,12,11,23]))

what is the molarity of a solution prepared by dissolving 15.0g of sodium hydroxide in enough water to make a total of 225 ml of solution​

Answers

Answer:

1.6666 g/mol = 1 [tex]\frac{2}{3}[/tex] g/mol

Explanation:

Molar mass of NaOH= 23+16+1 =40g/mol

Mols in 15g = 15/40 mol

If this was dissolved in 225ml of water molarity of the solution is

[tex]\frac{15}{40}[/tex] ÷ 225 x 1000 = 1.6666 g/mol = 1 [tex]\frac{2}{3}[/tex] g/mol

Final answer:

The molarity of the sodium hydroxide solution is calculated by dividing the number of moles of NaOH (0.375 moles) by the volume of the solution in liters (0.225 L), resulting in 1.667 M.

Explanation:

The molarity of a solution is determined by the number of moles of solute per liter of solution. To find the molarity of the solution, we need to know the molar mass of sodium hydroxide (NaOH), which is approximately 40 g/mol. First, we convert the mass of NaOH to moles:

Mass of NaOH = 15.0 g

Molar mass of NaOH = 40 g/mol

Moles of NaOH = Mass / Molar mass = 15.0 g / 40 g/mol = 0.375 moles

Second, we convert the volume of the solution from milliliters to liters:

Volume of solution = 225 mL

1 liter = 1000 mL

Volume in liters = 225 mL / 1000 = 0.225 liters

Finally, we calculate the molarity of the solution using the formula:

Molarity (M) = Moles of solute / Volume of solution in liters

Molarity (M) = 0.375 moles / 0.225 liters

Molarity (M) = 1.667 M

Therefore, the molarity of the sodium hydroxide solution is 1.667 M.

Which type of styles can be applied to a word, phrase, or sentence?
Format
Object
Paragraph
Character
Resume

Answers

Answer:

I think the answer is going to be paragraph

The types of styles that can be applied to a word, phrase, or sentence are the character style and paragraph style. Thus, the correct options for this question are C and D.

What do you mean by Character style?

Character style may be defined as a type of style that can be used for the word, phrase, or sentence in design. This type of style considerably remembers formatting for single characters, words, or phrases.

While Paragraph Style will remember the formatting applied to a whole paragraph. This type of style is most frequently applied to a section of text separated from other text by line breaks with the intention to fragment the literary work into short paragraphs.

Therefore, the character and paragraph styles are the types of styles that can be applied to a word, phrase, or sentence.

To learn more about Paragraph styles, refer to the link:

https://brainly.com/question/13149944

#SPJ2

Suppose you are currently in the /home/hnewman/os/fall/2013 directory and would like to navigate to /home/hnewman/discreteStructures/spring/2011 directory and would like to navigate using absolute path names. What command will you type in the shell? A. cd /home/hnewman/discreteStructures/spring/2011 B. cd discreteStructures/spring/2009 C. cd ../../..discreteStructures/spring/2009 D. cd ../../discreteStructures/spring/2009

Answers

Answer:

  A. cd /home/hnewman/discreteStructures/spring/2011

Explanation:

Nothing with 2009 in the pathname will get you where you want to go. The only reasonable answer choice is the first one:

  cd /home/hnewman/discreteStructures/spring/2011

Implement the logic function ( , , ) (0,4,5) f a b c m =∑ in 4 different ways. You have available 3to-8 decoders with active high (AH) or active low (AL) outputs and OR, AND, NOR and NAND gates with as many inputs as needed. In every case clearly indicate which is the Most Significant bit (MSb) and which is the Least Significant bit (LSb) of the decoder input.

Answers

Answer:

See explaination

Explanation:

Taking a look at the The Logic function, which states that an output action will become TRUE if either one “OR” more events are TRUE, but the order at which they occur is unimportant as it does not affect the final result. For example, A + B = B + A.

Alternatively the Most significant bit which is also known as the alt bit, high bit, meta bit, or senior bit, the most significant bit is the highest bit in binary.

See the attached file for those detailed logic functions designed with relation to the questions asked.

Use semaphore(s) to solve the following problem. There are three processes: P1, P2, and P3. Each process Pi has a segment of codes Ci, i=1, 2, 3. These three processes are executed only once, i.e., no repeat or loop at all, and their executions can start at any time. Your goal is to ensure that the execution of C1, C2, and C3 must satisfy the following conditions:
a. If C1 is executed ahead of C2 and C3, C2 must be executed ahead of C3.
b. Otherwise, C1 must be executed after both C2 and C3 are executed. In this case, the order of C2 and C3's execution doesn't matter. One of the possible execution orders is demonstrated below. Obviously, two other possible sequences in time are C2, C3, C1 and C3, C2, C1.
Please write your algorithm level code for semaphore initialization and usage in each code segment. [Hint: no if statements should ever be used. All you need is some semaphore function calls surrounding C1, C2, and C3 and their initial values.]

Answers

Answer:

See explaination

Explanation:

Here we will use two semaphore variables to satisfy our goal

We will initialize s1=1 and s2=1 globally and they are accessed by all 3 processes and use up and down operations in following way

Code:-

s1,s2=1

P1 P2 P3

P(s1)

P(s2)

C1

V(s2) .

P(s2). .

. C2

V(s1) .

P(s1)

. . C3

V(s2)

Explanation:-

The P(s1) stands for down operation for semaphore s1 and V(s1) stands for Up operation for semaphore s1.

The Down operation on s1=1 will make it s1=0 and our process will execute ,and down on s1=0 will block the process

The Up operation on s1=0 will unblock the process and on s1=1 will be normal execution of process

Now in the above code:

1)If C1 is executed first then it means down on s1,s2 will make it zero and up on s2 will make it 1, so in that case C3 cannot execute because P3 has down operation on s1 before C3 ,so C2 will execute by performing down on s2 and after that Up on s1 will be done by P2 and then C3 can execute

So our first condition gets satisfied

2)If C1 is not executed earlier means:-

a)If C2 is executed by performing down on S2 then s2=0,so definitely C3 will be executed because down(s2) in case of C1 will block the process P1 and after C3 execute Up operation on s2 ,C1 can execute because P1 gets unblocked .

b)If C3 is executed by performing down on s1 then s1=0 ,so definitely C2 will be executed now ,because down on s1 will block the process P1 and after that P2 will perform up on s1 ,so P1 gets unblocked

So C1 will be executed after C2 and C3 ,hence our 2nd condition satisfied.

Implement the A5/1 algorithm. Suppose that, after a particular step, the values of the register are: X = (x0, x1, …, x18) = (1010101010101010101) Y = (y0, y1, …, y21) = (1100110011001100110011) Z = (z0, z1, …, z22) = (11100001111000011110000) List the next 32 keystream bits and give the contents of X, Y, and Z after these 32 bits have been generated.

Answers

Answer:

Check the explanation

Explanation:

After a particular step the registers X, Y and Z values are as it is in the first attached image below.

Now calculate the key stream bit, s using the following formula:

key stream bit , s= x0 XOR y0 XOR z0

                       s= 1 XOR 1 XOR 1

           Hence, the 1st key bit stream ,s= 1

Now, for the next step we have to re calculate the contents of registers X, Y and Z as it is in the second attached image below.

For register X:

t= x5 XOR x2 XOR x1 XOR x0

= 0 XOR 1 XOR 0 XOR 1

t=0

For register Y:

t= y1 XOR y0

=1 XOR 1

t=0

For register Z:

t= z15 XOR z2 XOR z1 XOR z0

=1 XOR 1 XOR 1 XOR 1

t=0

Now, the contents of X, Y and X are as it is in the third attached image below.

Key stream bit, s= x0 XOR y0 XOR z0

                             S= 0 XOR 1 XOR 1

                             Hence the 2nd key stream bit, s= 0

The A5/1 algorithm generates keystream bits by shifting three LFSRs based on a majority bit mechanism and producing output bits through XOR operations. Following this process, the registers X, Y, and Z are updated, and the keystream is generated. The new register states and keystream give us the final output.

The A5/1 algorithm uses three Linear Feedback Shift Registers (LFSRs) named X, Y, and Z. Here are the initial states of the registers:

X = (1010101010101010101)Y = (1100110011001100110011)Z = (11100001111000011110000)

To generate the next 32 keystream bits and update the registers, the following steps are followed:

Identify the majority bit of X<11>, Y<11>, and Z<11>.Only the registers with bits equal to the majority bit are shifted.Shift each register, updating the bits according to their feedback taps (for X: positions 13, 16, 17, 18; for Y: positions 20, 21; for Z: position 7, 20, 21, 22).Compute the output bit as the XOR of bits X<18>, Y<21>, Z<22>.Repeat until 32 bits are produced.

After generating 32 keystream bits, the contents of the registers and the keystream are:

Keystream = (Provide the actual calculation here)X = (Updated state)Y = (Updated state)Z = (Updated state)

Write a class called (d) Teacher that has just a main method. The main method should construct a GradeBook for a class with two students, "Jack" and "Jill". Jack’s grades on the three tests for the class are 33, 55, and 77. Jill’s grades are 99, 66, and 33. After constructing the GradeBook object, main should use the instance methods of the GradeBook class to determine the name of the student with the highest average grades. Print the name of this student on the screen.

Answers

Answer:

The java program is given below.

import java.util.*;

class GradeBook  

{

//variables to hold all the given values

static int m11, m12, m13;

static int m21, m22, m23;

static String name1, name2;

//variables to hold the computed values

static double avg1, avg2;

//constructor initializing the variables with the given values

GradeBook()

{

name1 = "Jack";

m11 = 33;

m12 = 55;

m13 = 77;

name2 = "Jill";

m21 = 99;

m22 = 66;

m23 = 33;

}

//method to compute and display the student having highest average grade

static void computeAvg()

{

avg1=(m11+m12+m13)/3;

avg2=(m21+m22+m23)/3;

if(avg1>avg2)

System.out.println("Student with highest average is "+ name1);

else

System.out.println("Student with highest average is "+ name2);

}  

}

//contains only main() method

public class Teacher{  

public static void main(String[] args)

{

//object created

GradeBook ob = new GradeBook();

//object used to call the method

ob.computeAvg();

}

}

OUTPUT

Student with highest average is Jill

Explanation:

1. The class GradeBook declares all the required variables as static with appropriate data types, integer for grades and double for average grade.

2. Inside the constructor, the given values are assigned to the variables.

3. The method, computeAvg(), computes the average grade of both the students. The student having highest average grade is displayed using System.out.println() method.

4. Inside the class, Teacher, the main() method only has 2 lines of code.

5. The object of the class GradeBook is created.

6. The object is used to call the method, computeAvg(), which displays the message on the screen.

7. All the methods are also declared static except the constructor. The constructor cannot have any return type nor any access specifier.

8. The program does not takes any user input.

9. The program can be executed with different values of grades and names of the students.

(1) The given program outputs a fixed-height triangle using a * character. Modify the given program to output a right triangle that instead uses the user-specified triangle_char character. (1 pt) (2) Modify the program to use a loop to output a right triangle of height triangle_height. The first line will have one user-specified character, such as % or *. Each subsequent line will have one additional user-specified character until the number in the triangle's base reaches triangle_height. Output a space after each user-specified character, including a line's last user-specified character. (2 pts) Example output for triangle_char = % and triangle_height = 5:

Answers

Answer:

Following are the code to this question can be described as follows:

c= input('Input triangle_char: ') #defining variable c that input character value  

length = int(input('Enter triangle_height: ')) # Enter total height of triangle

for i in range(length): # loop for column values

   for j in range(i+1): #loop to print row values

       print(c,end=' ') #print value  

   print()# for new line

Output:

please find the attachment.

Explanation:

In the above python code, two variable "c and length" variables are declared, in variable c is used to input char variable value, in the next line, length variable is defined, that accepts total height from the user.

In the next line, two for loop is declared, it uses as nested looping, in which the outer loop prints column values and inner the loop is used to prints rows. To prints all the value the print method is used, which prints the user input character triangle.
Final answer:

The question asks how to modify a program to print a right triangle using a character and height defined by the user. The solution is to use a nested loop, wherein an outer loop specifies the number of rows equal to the triangle's height and the inner loop iterates over each row to print the specified character. The range of the inner loop increases with each outer loop iteration.

Explanation:

To modify the given program to output a right triangle using the user-specified character and of a specified height, we would implement a nested loop in the program. An outer loop would control the number of rows, which equals the triangle's height, and an inner loop would handle the printing of the user-specified character per line. The inner loop's range would increase with each iteration of the outer loop. Here's an example in Python:

triangle_char = input('Enter a character: ') triangle_height = int(input('Enter triangle height: ')) for i in range(1, triangle_height + 1):for j in range(i): print(triangle_char, end=' ') print()

The triangle_char variable is the character used to generate the triangle. The triangle_height variable determines the number of rows. The range() function in the loops determines how many times the loop executes.

Learn more about Programming Nested Loops here:

https://brainly.com/question/35123300

#SPJ11

2. Use inheritance to create a hierarchy of Exception classes -- EndOfSentenceException, PunctuationException, and CommaException. EndOfSentenceException is the parent class to PunctuationException, which is the parent class to CommaException. Test your classes in a Driver class with a main method that asks the user to input a sentence. If the sentence ends in anything except a period (.), exclamation point (!), or question mark (?), the program should throw a PunctuationException. If the sentence specifically ends in a comma, the program should throw a CommaException. Use a catch block to catch all EndOfSentenceExceptions, causing the program to print a message and terminate. If a general PunctuationException is caught, the program should print "The sentence does not end correctly." If a CommaException is caught, the program should print "You can't end a sentence in a comma." If there are no exceptions, the program should print "The sentence ends correctly." and terminate.

Answers

Answer:

See explaination

Explanation:

EndOfSentenceException.java

//Create a class EndOfSentenceException that

//extends the Exception class.

class EndOfSentenceException extends Exception

{

//Construtor.

EndOfSentenceException(String str)

{

System.out.println(str);

}

}

CommaException.java

//Create a class CommaException that extends the class

//EndOfSentenceException.

class CommaException extends EndOfSentenceException

{

//Define the constructor of CommaException.

public CommaException(String str)

{

super(str);

}

}

PunctuationException.java

//Create a class PunctuationException that extends the class

//EndOfSentenceException.

class PunctuationException extends EndOfSentenceException

{

//Constructor.

public PunctuationException(String str)

{

super(str);

}

}

Driver.java

//Include the header file.

import java.util.Scanner;

//Define the class Driver to check the sentence.

public class Driver {

//Define the function to check the sentence exceptions.

public String checkSentence(String str)

throws EndOfSentenceException

{

//Check the sentence ends with full stop,

//exclamation mark

//and question mark.

if(!(str.endsWith(".")) && !(str.endsWith("!"))

&& !(str.endsWith("?")))

{

//Check the sentence is ending with comma.

if(str.endsWith(","))

{

//Throw the CommaException.

throw new CommaException("You can't "

+ "end a sentence in a comma.");

}

//Otherwise.

else

{

//Throw PunctuationException.

throw new PunctuationException("The sentence "

+ "does not end correctly.");

}

}

//If the above conditions fails then

//return this message to the main function.

return "The sentence ends correctly.";

}

//Define the main function.

public static void main(String[] args)

{

//Create an object of Scanner

Scanner object = new Scanner(System.in);

//Prompt the user to enter the sentence.

System.out.println("Enter the sentence:");

String sentence=object.nextLine();

//Begin the try block.

try {

//Call the Driver's check function.

System.out.println(new

Driver().checkSentence(sentence));

}

//The catch block to catch the exception.

catch (EndOfSentenceException e)

{}

}

}

Other Questions
Which statement correctly describes the Soviet Unions relationships with its Eastern European neighbors after 1945?The Soviet Union helped them organize free elections.The Soviet Union allowed prewar governments to return to power.The Soviet Union set up states that were independent in name only.The Soviet Union allowed free rule in the satellite states. A feedback system controls the menstrual cycle. How does a female respondto a sharp drop in luteinizing hormone?A. With a gradual rise in the progesterone levelB. With the immediate release of a mature eggC. With the immediate beginning of a new cycleD. With a quick rise in the estrogen levelSomeone help me please a hospital did a ten year study on patients who used its services. one thousand patients were randomly selected and followed over a period of ten years to determine the average number of visits per year. by the end of the year period some of the patients had left the area. identify the problem with the pool Complete the statement about figures on the graph. Parts A and create a figure on the coordinate plane that has point symmetry about the origin. Hoy comienzan mis vacaciones por el sur de Chile. Voy a ir a cinco ciudades diferentes: Temuco, Osorno, Villarrica, PChilo. Hice reservaciones en el hotel de Pucn. Voy a estar alli por 3 das, despues ir a Villarrica a visitar el ParqueNacional Petrohu. Luego visitar Chilo y Temuco para sacar muchas fotos del impresionante paisaje all. En Osornocomprar recuerdos para mi familia y terminar otra vez en Pucon donde me preparar para regresar.How many cities is this person going to visit in Chile?fourthreenonefive What is the name of the girl Piri meets at his new job Your bosses at the residential contracting firm has asked you to help them decide about whether they should keep a particular item of construction equipment or accept an offer for sale. The equipment cost $126,000 new and it has a useful life of eight years.The firm has been using a double declining balance (DDB) method of depreciation and this is the third year of ownership. Your firm has received an offer to purchase the item (at the end of this third year of ownership) for $60,000. However, your bosses only will sell if doing so will make a profit. To help your bosses decide whether or not they should sell the equipment, calculate the remaining book value at the end of year 3 (the anticipated time of sale). Find the solutions of the quadratic equation 3x^2 + 9x + 17 = 0 On January 15, 1990, Anders brought an action against Barnes for breach of a contract for the sale of electronic parts. The breach occurred on January 10, 1986, and Anders discovered the breach on January 20, 1986. The state statute of limitations for contract actions is five years. Barnes raised the UCC statute of limitations as a defense to the action. DISCUSS, Is this defense valid? WHY 0R WHY NOT...WHAT ARE THE LEGAL ISSUES? NEED HELP AS AS SOON AS POSSIBLE Something that brings about an action or consequence is a(n) a)CAUSE b)central idea c)offect d)suporting detaile Being proactive means you...a. take responsibility for your attitude, actions, and consequences.b. wait for something to happen to you.c. think about possible solutions and options.d. Both A & C The start of the Korean War in the 1950s is MOST associated with which of these? The Great DepressionThe spread of CommunismThe spread of Nazi governmentsThe invasion by the Soviet Union Which best describes the organisms in this kingdom? They are autotrophic and have eukaryotic cellsThey are made of prokaryotic cellsThey are multicellular and do not have cell wallsThey are always single celled and produce their own food A small car of mass m and a large car of mass 4m drive along a highway at constant speeds VS and VL. They approach a curve of radius R. The small and large cars have accelerations as and aL respectively, as they travel around the curve. The magnitude of as is twice of that of aL. How does the speed of the small car VS compare to the speed of the large car VL as they move around the curve Why does the animator use a wide shot of Cyprus,lutra and the tarcliraptor? Which of these is primarily responsible for the control of the money supply in the United States?A)the U.S. TreasuryB)the Federal ReserveC)the executive branchD)the legislative branch 2.3 THINK: Florida Part 277In 1840, the population of Florida was about 54,500. Between 1840 and 1860,the population grew exponentially, increasing by about 60% each decade.The number of decades can be calculated when estimating population.1. How many decades are represented between 1840 and 1850?2. How many decades are represented between 1840 and 1860?Reply as 1-2 The sooner the better. How did immigration after the Civil War affect Texas culture? Write the absolute value equations in the form xb=c (where b is a number and c can be either number or an expression) that have the following solution sets:aTwo solutions: x=2, x=14. Steam Workshop Downloader