New Semester
Started
Get
50% OFF
Study Help!
--h --m --s
Claim Now
Question Answers
Textbooks
Find textbooks, questions and answers
Oops, something went wrong!
Change your search query and then try again
S
Books
FREE
Study Help
Expert Questions
Accounting
General Management
Mathematics
Finance
Organizational Behaviour
Law
Physics
Operating System
Management Leadership
Sociology
Programming
Marketing
Database
Computer Network
Economics
Textbooks Solutions
Accounting
Managerial Accounting
Management Leadership
Cost Accounting
Statistics
Business Law
Corporate Finance
Finance
Economics
Auditing
Tutors
Online Tutors
Find a Tutor
Hire a Tutor
Become a Tutor
AI Tutor
AI Study Planner
NEW
Sell Books
Search
Search
Sign In
Register
study help
computer science
java concepts late objects
Java Concepts Late Objects 3rd Edition Cay S. Horstmann - Solutions
Simulate a circuit for controlling a hallway light that has switches at both ends of the hallway. Each switch can be up or down, and the light can be on or off. Toggling either switch turns the lamp on or off. Provide methodspublic int getFirstSwitchState() // 0 for down, 1 for uppublic int
Consider the Menu class in Worked Example 8.1. What is displayed when the following calls are executed?Menu simpleMenu = new Menu();simpleMenu.addOption("Ok");simpleMenu.addOption("Cancel");int response = simpleMenu.getInput();
A Person has a name (just a first name for simplicity) and friends. Store the names of the friends in a string, separated by spaces. Provide a constructor that constructs a person with a given name and no friends. Provide methodspublic void befriend(Person p)public void unfriend(Person p)public
Simulate a tally counter that can be used to admit a limited number of people. First, the limit is set with a callpublic void setLimit(int maximum)If the count button was clicked more often than the limit, simulate an alarm by printing out a message “Limit exceeded”.
What is a checked exception? What is an unchecked exception? Give an example for each. Which exceptions do you need to declare with the throws reserved word?
Using the mechanism described in Special Topic 7.1, write a program that reads all data from a web page and prints all hyperlinks of the formlink textExtra credit if your program can follow the links that it finds and find links in those web pages as well. (This is the method that search engines
Write a program that asks the user for a file name and prints the number of characters, words, and lines in that file.
What is the difference between throwing an exception and catching an exception?
Find an interesting data set in CSV format (or in spreadsheet format, then use a spreadsheet to save the data as CSV). Using the CSVReader program from Exercise P7.5, read the data and compute a summary, such as the maximum, minimum, or average of one of the columns.Data from Exercise P7.5,The CSV
Write a program that reads a file containing two columns of floating-point numbers. Prompt the user for the file name. Print the average of each column.
Repeat Exercise E7.4, but allow the user to specify the file name on the commandline. If the user doesn’t specify any file name, then prompt the user for the name.Data from Exercise E7.4,Write a program that reads a file containing text. Read each line and send it to the output file, preceded by
If a program Woozle is started with the commandjava Woozle -Dname=piglet -I\eeyore -v heff.txt a.txt lump.txtwhat are the values of args[0], args[1], and so on?
The CSV (or comma-separated values) format is commonly used for tabular data. Each table row is a line, with columns separated by commas. Items may be enclosed in quotation marks, and they must be if they contain commas or quotation marks. Quotation marks inside quoted fields are doubled. Here is a
Write a program that reads a file containing text. Read each line and send it to the output file, preceded by line numbers. If the input file is Mary had a little lamb Whose fleece was white as snow. And everywhere that Mary went, The lamb was sure to go! then the program produces the output file/*
How do you open a file whose name contains a backslash, like c:temp\output.dat?
Write a program that reads a file, removes any blank lines at the beginning or end of the file, and writes the remaining lines back to the same file.
What happens when you write to a Print Writer without closing it? Produce a test program that demonstrates how you can lose data.
Write a program that reads a file in the same format as worked_example_1/babynames.txt and prints all names that are both boy and girl names (such as Alexis or Morgan).
Write a program that reads a file, removes any blank lines, and writes the non-blank lines back to the same file.
What happens if you try to open a file for writing, but the file or device is write protected (sometimes called read-only)? Try it out with a short test program.
Write a program that reads in worked_example_1/babynames.txt and produces two files, boynames.txt and girlnames.txt, separating the data for the boys and girls.
Write a program that carries out the following tasks:Open a file with the name hello.txt. Store the message “Hello, World!” in the file. Close the file. Open the same file again. Read the message into a string variable and print it.
What happens if you try to open a file for reading that doesn’t exist? What happens if you try to open a file for writing that doesn’t exist?
Get the data for names in prior decades from the Social Security Administration. Paste the table data in files named babynames80s.txt, etc. Modify the worked_example_1/ BabyNames.java program so that it prompts the user for a file name. The numbers in the files have comma separators, so modify the
True or false?a. All elements of an array list are of the same type.b. Array list index values must be integers.c. Array lists cannot contain strings as elements.d. Array lists can change their size, getting larger or smaller.e. A method cannot return an array list.f. A method cannot change the
How do you perform the following tasks with array lists in Java?a. Test that two array lists contain the same elements in the same order.b. Copy one array list to another.c. Fill an array list with zeroes, overwriting all elements in it.d. Remove all elements from an array list.
True or false?a. All elements of an array are of the same type.b. Arrays cannot contain strings as elements.c. Two-dimensional arrays always have the same number of rows and columns.d. Elements of different columns in a two-dimensional array can have different types.e. A method cannot return a
Write pseudocode for an algorithm that fills the first and last column as well as the first and last row of a two-dimensional array of integers with –1.
Write a method that swaps two columns of a two-dimensional array.
Write Java statements for performing the following tasks with an array declared asint[][] values = new int[ROWS][COLUMNS];• Fill all entries with 0.• Fill elements alternately with 0s and 1s in a checkerboard pattern.• Fill only the elements at the top and bottom row with zeroes.• Compute
Write a method that swaps two rows of a two-dimensional array.
Develop an algorithm for finding the most frequently occurring value in an array of numbers. Use a sequence of coins. Place paper clips below each coin that count how many other coins of the same value are in the sequence. Give the pseudocode for an algorithm that yields the correct answer, and
Write a method that checks whether two two-dimensional arrays are equal; that is, whether they have the same number of rows and columns, and corresponding elements are equal.
Write a method that checks whether all elements in a two-dimensional array are distinct.
Solve the problem described in Section 6.5 by sorting the array first. How do you need to modify the algorithm for computing the total?
Write a method that checks whether all elements in a two-dimensional array are identical.
You are given two arrays denoting x- and y-coordinates of a set of points in the plane. For plotting the point set, we need to know the x- and y-coordinates of the smallest rectangle containing the points. How can you obtain these values from the fundamental algorithms in Section 6.3?
Write a method that finds the first occurrence of a value in a two-dimensional array. Return an int[] array of length 2 with the row and column, or null if the value was not found.
What is wrong with the following method that aims to fill an array with random numbers?public static void fillWithRandomNumbers(double[] values){double[] numbers = new double[values.length];for (int i = 0; i < numbers.length; i++){numbers[i] = Math.random();}values = numbers;}
Write a method that counts the number of distinct elements in an ArrayList. Do not modify the array list.
A run is a sequence of adjacent repeated values. Give pseudocode for computing the ength of the longest run in an array. For example, the longest run in the array with elements 1 2 5 5 3 1 2 4 3 2 2 2 2 3 6 5 5 6 3 1has length 4.
Write a method that modifies an ArrayList, moving all strings starting with an uppercase letter to the front, without otherwise changing the order of the elements.
Suppose values is a sorted array of integers. Give pseudocode that describes how a new value can be inserted in its proper position so that the resulting array stays sorted.
Write a methodpublic static ArrayList mergeSorted(ArrayList a,ArrayList b)that merges two sorted array lists, producing a new sorted array list. Keep an index into each array list, indicating how much of it has been processed already. Each time, append the smallest unprocessed element from either
Give pseudocode for an algorithm that removes all negative values from an array, preserving the order of the remaining elements.
Write a methodpublic static ArrayList merge(ArrayList a, ArrayList b)that merges two array lists, alternating elements from both array lists. If one array list is shorter than the other, then alternate as long as you can and then append the remaining elements from the longer array list. For
Give pseudocode for an algorithm that rotates the elements of an array by one position, moving the initial element to the end of the array, like this: 2157 11 13 ///// 357 11 13 2
Using the technique of Special Topic 4.3, generate the image of a sine wave. Draw a line of pixels for every five degrees.
Write a methodpublic static ArrayList append(ArrayList a, ArrayList b)that appends one array list after another. For example, if a is 1 4 9 16 and b is 9 7 4 9 11 then append returns the array list1 4 9 16 9 7 4 9 11
Consider the following loop for collecting all elements that match a condition; in this case, that the element is larger than 100.ArrayList matches = new ArrayList();for (double element : values){if (element > 100){matches.add(element);}}Trace the flow of the loop, where values contains the
Using the technique of Special Topic 4.3, generate the image of a checkerboard.
Improve the program of Exercise E6.15 by adding captions for each bar. Prompt the user for the captions and data values. The output should look like this:Egypt **********************France ****************************************Japan ****************************Uruguay
Write a program that models the movement of an object with mass m that is attached to an oscillating spring. When a spring is displaced from its equilibrium position by an amount x, Hooke’s law states that the restoring force is F = –kx where k is a constant that depends on the spring. (Use 10
Improve the program of Exercise E6.15 to work correctly when the data set contains negative values.Data from Exercise E6.15Repeat Exercise E6.15, but make the bars vertical, with the tallest bar twenty asterisks high. *... ...
For the operations on partially filled arrays below, provide the header of a method. Do not implement the methods.a. Sort the elements in decreasing order.b. Print all elements, separated by a given string.c. Count how many elements are less than a given value.d. Remove all elements that are less
Modify the ch06/animation/BlockAnimation.java program to show an animated sine wave. In the ith frame, shift the sine wave by i degrees.
Repeat Exercise E6.15, but make the bars vertical, with the tallest bar twenty asterisks high.Data from Exercise E6.15,Write a program that reads a sequence of input values and displays a bar chart of the values, using asterisks, like
Sample values from an experiment often need to be smoothed out. One simple approach is to replace each value in an array with the average of the value and its two neighboring values (or one neighboring value if it is at either end of the array). Implement a methodpublic static void smooth(double[]
Write a program that reads a sequence of input values and displays a bar chart of the values, using asterisks, like this:**********************************************************************************************************************************You may assume that all values are positive.
You are given a two-dimensional array of values that give the height of a terrain at different points in a square. Write a method.that prints out a flood map, showing which of the points in the terrain would be flooded if the water level was the given value. In the flood map, print a * for each
Write a method that computes the average of the neighbors of a two-dimensional array element in the eight directions shown in Figure 14. public static double neighborAverage(int[][] values, int row, int column) However, if the element is located at the boundary of the array, only include the
Sounds can be represented by an array of “sample values” that describe the intensity of the sound at a point in time. The program ch06/sound/SoundEffect. java reads a sound file (in WAV format), calls a method process for processing the sample values, and saves the sound file. Your task is to
Write a program that produces ten random permutations of the numbers 1 to 10. To generate a random permutation, you need to fill an array with the numbers 1 to 10 so that no two entries of the array have the same contents. You could do it by brute force, by generating random values until you have a
Write a loop that reads ten numbers and a second loop that displays them in the opposite order from which they were entered.
Write a program that contains a bounds error. Run the program. What happens on your computer?
Write a program that generates a sequence of 20 random values between 0 and 99 in an array, prints the sequence, sorts it, and prints the sorted sequence. Use the sort method from the standard Java library.
What is an index of an array? What are the legal index values? What is a bounds error?
A supermarket wants to reward its best customer of each day, showing the customer’s name on a screen in the supermarket. For that purpose, the customer’s purchase amount is stored in an ArrayList and the customer’s name is stored in a correspondingArrayList.Implement a methodpublic static
Write a methodpublic static boolean sameElements(int[] a, int[] b)that checks whether two arrays have the same elements in some order, with the same multiplicities. For example,1 4 9 16 9 7 4 9 11 and 11 1 4 9 16 9 7 4 9 would be considered identical, but 1 4 9 16 9 7 4 9 11 and 11 11 7 9 16 4 1 4
What is wrong with each of the following code segments?a. ArrayList values = new ArrayList();b. ArrayList values = new ArrayList();c. ArrayList values = new ArrayList;d. ArrayList values = new ArrayList();for (int i = 1; i <= 10; i++){values.set(i - 1, i * i);}e. ArrayList values;for (int i = 1;
A pet shop wants to give a discount to its clients if they buy one or more pets and at least five other items. The discount is equal to 20 percent of the cost of the other items, but not the pets. Implement a methodpublic static void discount(double[] prices, boolean[] isPet, int nItems)The method
Write a methodpublic static boolean sameSet(int[] a, int[] b)that checks whether two arrays have the same elements in some order, ignoring duplicates. For example, the two arrays1 4 9 16 9 7 4 9 11 and 11 11 7 9 16 4 1 would be considered identical. You will probably need one or more helper methods.
Rewrite the following loops, using the enhanced for loop construct. Here, values is an array of floating-point numbers.a. for (int i = 0; i < values.length; i++) { total = total + values[i]; }b. for (int i = 1; i < values.length; i++) { total = total + values[i]; }c. for (int i = 0; i <
The Game of Life is a well-known mathematical game that gives rise to amazingly complex behavior, although it can be specified by a few simple rules. (It is not actually a game in the traditional sense, with players competing for a win.) Here are the rules. The game is played on a rectangular
Write a methodpublic static boolean equals(int[] a, int[] b)that checks whether two arrays have the same elements in the same order.
Rewrite the following loops without using the enhanced for loop construct. Here, values is an array of floating-point numbers.a. for (double x : values) { total = total + x; }b. for (double x : values) { if (x == target) { return true; } }c. int i = 0;for (double x : values) { values[i] = 2 * x;
Write a program that plays tic-tac-toe. The tic-tac-toe game is played on a 3 × 3 grid as in the photo at right. The game is played by two players, who take turns. The first player marks moves with a circle, the second with a cross. The player who has formed a horizontal, vertical, or diagonal
Write enhanced for loops for the following tasks.a. Printing all elements of an array in a single row, separated by spaces.b. Computing the product of all elements in an array.c. Counting how many elements in an array are negative.
A theater seating chart is implemented as a two-dimensional array of ticket prices, like this:Write a program that prompts users to pick either a seat or a price. Mark sold seats by changing the price to 0. When a user specifies a seat, make sure it is available. When a user specifies a price, find
Write a method that reverses the sequence of elements in an array. For example, if you call the method with the array1 4 9 16 9 7 4 9 11 then the array is changed to 11 9 4 7 9 16 9 4 1
What is wrong with each of the following code segments?a. int[] values = new int[10];for (int i = 1; i <= 10; i++){values[i] = i * i;}b. int[] values;for (int i = 0; i < values.length; i++){values[i] = i * i;}
Implement the following algorithm to construct magic n × n squares; it works only if n is odd.Set row = n - 1, column = n / 2.For k = 1 ... n * nPlace k at [row][column].Increment row and column.If the row or column is n, replace it with 0.If the element at [row][column] has already been filledSet
Compute the alternating sum of all elements in an array. For example, if your program reads the input 1 4 9 16 9 7 4 9 11 then it computes 1 – 4 + 9 – 16 + 9 – 7 + 4 – 9 + 11 = –2
Write Java code for a loop that simultaneously computes both the maximum and minimum of an array.
Magic squares. An n × n matrix that is filled with the numbers 1, 2, 3, . . ., n2 is a magic square if the sum of the elements in each row, in each column, and in the two diagonals is the same value. Write a program that reads in 16 values from the keyboard and tests whether they form a magic
Write a method public static void removeMin that removes the minimum value from a partially filled array without calling other methods.
Write a loop that fills an array values with ten random numbers between 1 and 100. Write code for two nested loops that fill values with ten different random numbers between 1 and 100.
In this assignment, you will model the game of Bulgarian Solitaire. The game starts with 45 cards. (They need not be playing cards. Unmarked index cards work just as well.) Randomly divide them into some number of piles of random size. For example, you might start with piles of size 20, 5, 1, 9,
Write a method sumWithoutSmallest that computes the sum of an array of values, except for the smallest one, in a single loop. In the loop, update the sum and the smallest value. After the loop, return the difference.
Consider the following array:int[] a = { 1, 2, 3, 4, 5, 4, 3, 2, 1, 0 };What are the contents of the array a after the following loops complete?a. for (int i = 1; i < 10; i++) { a[i] = a[i - 1]; }b. for (int i = 9; i > 0; i--) { a[i] = a[i - 1]; }c. for (int i = 0; i < 9; i++) { a[i] = a[i
It is a well-researched fact that men in a restroom generally prefer to maximize their distance from already occupied stalls, by occupying the middle of the longest sequence of unoccupied places. For example, consider the situation where ten stalls are empty._ _ _ _ _ _ _ _ _ _The first visitor
Consider the following array:int[] a = { 1, 2, 3, 4, 5, 4, 3, 2, 1, 0 };What is the value of total after the following loops complete?a. int total = 0;for (int i = 0; i < 10; i++) { total = total + a[i]; }b. int total = 0;for (int i = 0; i < 10; i = i + 2) { total = total + a[i]; }c. int
Write array methods that carry out the following tasks for an array of integers. For each method, provide a test program.a. Swap the first and last elements in the array.b. Shift all elements by one to the right and move the last element into the first position. For example, 1 4 9 16 25 would be
Write a program that generates a sequence of 20 random die tosses in an array and that prints the die values, marking only the longest run, like this: 1 2 5 5 3 1 2 4 3 (2 2 2 2) 3 6 5 5 6 3 1 If there is more than one run of maximum length, mark the first one.
Write code that fills an array values with each set of numbers below. a. 1 3 4 5 6 7 8 9. 10 b. 0 c. 1 2 4 6 8 10 12 14 16 18 20 4 9 16 25 36 49 64 81 100 d. 0 e. 1 f. 0 4 16 9. 4 9. 11 1 9.0 1 4 1 2 14 a 00 O Om ON 2. 22
A run is a sequence of adjacent repeated values. Write a program that generates a sequence of 20 random die tosses in an array and that prints the die values, marking the runs by including them in parentheses, like this:1 2 (5 5) 3 1 2 4 3 (2 2 2 2) 3 6 (5 5) 6 3 1Use the following pseudocode:inRun
Write a program that initializes an array with ten random integers and then prints four lines of output, containing• Every element at an even index.• Every even element.• All elements in reverse order.• Only the first and last element.
Carry out the following tasks with an array:a. Allocate an array a of ten integers.b. Put the number 17 as the initial element of the array.c. Put the number 29 as the last element of the array.d. Fill the remaining elements with –1.e. Add 1 to each element of the array.f. Print all elements of
The drag force on a car is given bywhere ρ is the density of air (1.23 kg ∕ m3), v is the velocity in units of m ∕ s, A is the projected area of the car (2.5 m2), and CD is the drag coefficient (0.2). The amount of power in watts required to overcome such drag force is P = FDv, and the
Electric wire, like that in the photo, is a cylindrical conductor covered by an insulating material. The resistance of a piece of wire is given by the formulawhere ρ is the resistivity of the conductor, and L, A, and d are the length, cross sectional area, and diameter of the wire. The resistivity
Showing 100 - 200
of 835
1
2
3
4
5
6
7
8
9
Step by Step Answers