Write Programs That Read a Line of Input as a String and Print Only the Uppercase Letters
1.5 Input and Output
In this section we extend the set of unproblematic abstractions (command-line input and standard output) that nosotros accept been using every bit the interface between our Java programs and the outside earth to include standard input, standard drawing, and standard audio. Standard input makes it convenient for us to write programs that process arbitrary amounts of input and to collaborate with our programs; standard describe makes it possible for us to work with graphics; and standard audio adds audio.
Bird's-middle view.
A Java program takes input values from the command line and prints a string of characters every bit output. By default, both command-line arguments and standard output are associated with an application that takes commands, which we refer to equally the final window.
- Command-line arguments. All of our classes take a main() method that takes a String assortment args[] as argument. That array is the sequence of command-line arguments that nosotros type. If we intend for an argument to be a number, we must use a method such every bit Integer.parseInt() to convert information technology from String to the appropriate blazon.
- Standard output. To impress output values in our programs, nosotros have been using System.out.println(). Coffee sends the results to an abstract stream of characters known as standard output. Past default, the operating system connects standard output to the terminal window. All of the output in our programs so far has been appearing in the terminal window.
RandomSeq.java uses this model: Information technology takes a command-line statement n and prints to standard output a sequence of n random numbers betwixt 0 and one.
To complete our programming model, we add together the following libraries:
- Standard input. Read numbers and strings from the user.
- Standard drawing. Plot graphics.
- Standard audio. Create sound.
Standard output.
Java's
System.out.print()and
Organisation.out.println()methods implement the basic standard output abstraction that nosotros need. Nevertheless, to treat standard input and standard output in a uniform mode (and to provide a few technical improvements), we use similar methods that are divers in our StdOut library:
Java'south
print()and
println()methods are the ones that you have been using. The
printf()method gives u.s. more control over the advent of the output.
- Formatted printing basics. In its simplest form, printf() takes 2 arguments. The first argument is called the format cord. It contains a conversion specification that describes how the second argument is to exist converted to a string for output.
- Format string. The format cord tin contain characters in addition to those for the conversion specification. The conversion specification is replaced by the argument value (converted to a cord every bit specified) and all remaining characters are passed through to the output.
- Multiple arguments. The printf() function tin can have more than two arguments. In this case, the format string volition accept an boosted conversion specification for each boosted argument.
Here is more documentation on printf format string syntax.
Standard input.
Our StdIn library takes data from a standard input stream that contains a sequence of values separated past whitespace. Each value is a cord or a value from one of Java'due south archaic types. One of the cardinal features of the standard input stream is that your program consumes values when it reads them. Once your program has read a value, it cannot back upward and read it over again. The library is defined by the post-obit API:
We now consider several examples in item.
- Typing input. When you employ the java control to invoke a Java program from the command line, you lot actually are doing three things: (1) issuing a command to showtime executing your program, (2) specifying the values of the command-line arguments, and (3) beginning to define the standard input stream. The string of characters that y'all type in the terminal window after the command line is the standard input stream. For instance, AddInts.java takes a control-line statement n, then reads north numbers from standard input and adds them, and prints the result to standard output:
- Input format. If you type abc or 12.2 or true when StdIn.readInt() is expecting an int, and then it will respond with an InputMismatchException. StdIn treats strings of consecutive whitespace characters as identical to ane space and allows you to delimit your numbers with such strings.
- Interactive user input. TwentyQuestions.java is a simple example of a programme that interacts with its user. The programme generates a random integer and then gives clues to a user trying to judge the number. The fundamental departure between this programme and others that we have written is that the user has the power to modify the command flow while the program is executing.
- Processing an capricious-size input stream. Typically, input streams are finite: your program marches through the input stream, consuming values until the stream is empty. But in that location is no brake of the size of the input stream. Average.java reads in a sequence of real numbers from standard input and prints their boilerplate.
Redirection and pipage.
For many applications, typing input information as a standard input stream from the terminal window is untenable because doing and then limits our program'south processing power by the amount of information that nosotros can type. Similarly, nosotros often desire to save the data printed on the standard output stream for later apply. We can use operating arrangement mechanisms to address both problems.
- Redirecting standard output to a file. By adding a simple directive to the command that invokes a program, we tin can redirect its standard output to a file, either for permanent storage or for input to some other plan at a afterward fourth dimension. For example, the control
- Redirecting standard output from a file. Similarly, we can redirect standard input and so that StdIn reads data from a file instead of the terminal window. For case, the control
- Connecting two programs. The most flexible fashion to implement the standard input and standard output abstractions is to specify that they are implemented by our own programs! This machinery is called pipe. For case, the following command
- Filters. For many common tasks, it is convenient to remember of each program as a filter that converts a standard input stream to a standard output stream in some way, RangeFilter.java takes two control-line arguments and prints on standard output those numbers from standard input that fall within the specified range.
Your operating system as well provides a number of filters. For instance, the sort filter puts the lines on standard input in sorted order:
% java RandomSeq 5 | sort 0.035813305516568916 0.14306638757584322 0.348292877655532103 0.5761644592016527 0.9795908813988247
% java RandomSeq 1000 | more
Standard drawing.
Now we introduce a simple brainchild for producing drawings as output. We imagine an abstract drawing device capable of cartoon lines and points on a two-dimensional canvas. The device is capable of responding to the commands that our programs issue in the form of calls to static methods in StdDraw. The primary interface consists of ii kinds of methods: drawing commands that cause the device to take an action (such as drawing a line or drawing a indicate) and control commands that set parameters such as the pen size or the coordinate scales.
- Basic drawing commands. We first consider the drawing commands:
Your get-go drawing. The HelloWorld for graphics programming with StdDraw is to draw a triangle with a point inside. Triangle.java accomplishes this with iii calls to StdDraw.line() and one call to StdDraw.point().
- Control commands. The default canvass size is 512-by-512 pixels and the default coordinate arrangement is the unit of measurement square, but we often want to describe plots at different scales. Also, we frequently want to draw line segments of different thickness or points of different size from the standard. To suit these needs, StdDraw has the following methods:
StdDraw.setXscale(x0, x1); StdDraw.setYscale(y0, y1);
- Filtering data to a standard drawing. PlotFilter.coffee reads a sequence of points divers by (x, y) coordinates from standard input and draws a spot at each indicate. It adopts the convention that the first iv numbers on standard input specify the bounding box, then that it can calibration the plot.
% java PlotFilter < The states.txt
- Plotting a function graph. FunctionGraph.coffee plots the function y = sin(4x) + sin(20x) in the interval (0, π). There are an space number of points in the interval, then we have to make do with evaluating the role at a finite number of points within the interval. We sample the function by choosing a ready of x-values, then computing y-values past evaluating the part at each 10-value. Plotting the part by connecting successive points with lines produces what is known equally a piecewise linear approximation.
- Filtering data to a standard drawing. PlotFilter.coffee reads a sequence of points divers by (x, y) coordinates from standard input and draws a spot at each indicate. It adopts the convention that the first iv numbers on standard input specify the bounding box, then that it can calibration the plot.
- Outline and filled shapes. StdDraw also includes methods to draw circles, rectangles, and arbitrary polygons. Each shape defines an outline. When the method name is merely the shape name, that outline is traced by the drawing pen. When the method name begins with filled, the named shape is instead filled solid, not traced.
- Text and color. To annotate or highlight various elements in your drawings, StdDraw includes methods for drawing text, setting the font, and setting the the ink in the pen.
- Double buffering. StdDraw supports a powerful reckoner graphics feature known every bit double buffering. When double buffering is enabled past calling enableDoubleBuffering(), all cartoon takes place on the offscreen canvas. The offscreen canvass is not displayed; it exists only in computer retention. Only when you telephone call bear witness() does your drawing get copied from the offscreen canvas to the onscreen canvass, where it is displayed in the standard drawing window. You can think of double buffering as collecting all of the lines, points, shapes, and text that you tell it to describe, and then drawing them all simultaneously, upon request. 1 reason to apply double buffering is for efficiency when performing a large number of drawing commands.
- Computer animations. Our most important utilize of double buffering is to produce figurer animations, where we create the illusion of motion by rapidly displaying static drawings. We can produce animations past repeating the post-obit 4 steps:
- Articulate the offscreen sail.
- Draw objects on the offscreen
- Copy the offscreen canvass to the onscreen sail.
- Expect for a brusque while.
In support of these steps, the StdDraw has several methods:
The "Hello, World" program for animation is to produce a black brawl that appears to move effectually on the sail, bouncing off the boundary according to the laws of elastic collision. Suppose that the ball is at position (x, y) and we want to create the impression of having it move to a new position, say (x + 0.01, y + 0.02). We practise so in 4 steps:
- Articulate the offscreen sheet to white.
- Draw a black brawl at the new position on the offscreen canvas.
- Copy the offscreen sheet to the onscreen canvas.
- Expect for a short while.
To create the illusion of movement, BouncingBall.coffee iterates these steps for a whole sequence of positions of the ball.
- Images. Our standard depict library supports drawing pictures too equally geometric shapes. The control StdDraw.motion-picture show(10, y, filename) plots the epitome in the given filename (either JPEG, GIF, or PNG format) on the canvass, centered on (x, y). BouncingBallDeluxe.java illustrates an case where the billowy ball is replaced by an image of a lawn tennis ball.
- User interaction. Our standard describe library likewise includes methods so that the user can interact with the window using the mouse.
double mouseX() render x-coordinate of mouse double mouseY() render y-coordinate of mouse boolean mousePressed() is the mouse currently beingness pressed?
- A first example. MouseFollower.java is the HelloWorld of mouse interaction. It draws a blueish ball, centered on the location of the mouse. When the user holds down the mouse button, the ball changes color from blue to cyan.
- A uncomplicated attractor. OneSimpleAttractor.java simulates the motion of a blue ball that is attracted to the mouse. It also accounts for a drag forcefulness.
- Many simple attractors. SimpleAttractors.java simulates the motion of 20 blue balls that are attracted to the mouse. It likewise accounts for a drag force. When the user clicks, the balls disperse randomly.
- Springs. Springs.java implements a jump system.
Standard audio.
StdAudio is a library that you tin employ to play and manipulate sound files. Information technology allows yous to play, manipulate and synthesize sound.
We introduce some some bones concepts backside one of the oldest and most important areas of reckoner scientific discipline and scientific computing: digital bespeak processing.
- Concert A. Concert A is a sine wave, scaled to oscillate at a frequency of 440 times per second. The office sin(t) repeats itself once every 2π units on the x-centrality, and then if we measure t in seconds and plot the function sin(2πt × 440) we get a curve that oscillates 440 times per second. The amplitude (y-value) corresponds to the volume. We assume information technology is scaled to be between −1 and +one.
- Other notes. A simple mathematical formula characterizes the other notes on the chromatic scale. They are divided every bit on a logarithmic (base 2) scale: there are twelve notes on the chromatic calibration, and nosotros go the ith notation above a given note by multiplying its frequency by the (i/12)th power of ii.
- Sampling. For digital sound, we represent a curve by sampling it at regular intervals, in precisely the same manner as when we plot function graphs. Nosotros sample sufficiently often that we take an accurate representation of the curve—a widely used sampling rate is 44,100 samples per second. It is that simple: we stand for sound as an array of numbers (existent numbers that are between −1 and +ane).
int SAMPLING_RATE = 44100; double hz = 440.0; double duration = 10.0; int north = (int) (SAMPLING_RATE * elapsing); double[] a = new double[n+i]; for (int i = 0; i <= n; i++) { a[i] = Math.sin(two * Math.PI * i * hz / SAMPLING_RATE); } StdAudio.play(a);
- Play that melody. PlayThatTune.java is an example that shows how easily nosotros can create music with StdAudio. It takes notes from standard input, indexed on the chromatic calibration from concert A, and plays them on standard audio.
Exercises
- Write a program MaxMin.java that reads in integers (equally many every bit the user enters) from standard input and prints out the maximum and minimum values.
- Write a program Stats.coffee that takes an integer command-line statement northward, reads northward floating-point numbers from standard input, and prints their hateful (boilerplate value) and sample standard deviation (square root of the sum of the squares of their differences from the average, divided by n−1).
- Write a program LongestRun.java that reads in a sequence of integers and prints out both the integer that appears in a longest consecutive run and the length of the run. For example, if the input is 1 2 two 1 5 i 1 vii 7 7 7 i i, then your program should print Longest run: 4 consecutive 7s.
- Write a program WordCount.java that reads in text from standard input and prints out the number of words in the text. For the purpose of this exercise, a discussion is a sequence of non-whitespace characters that is surrounded by whitespace.
- Write a program Closest.java that takes three floating-bespeak command-line arguments \(10, y, z\), reads from standard input a sequence of point coordinates \((x_i, y_i, z_i)\), and prints the coordinates of the point closest to \((x, y, z)\). Think that the foursquare of the altitude between \((x, y, z)\) and \((x_i, y_i, z_i)\) is \((x - x_i)^ii + (y - y_i)^2 + (z - z_i)^2\). For efficiency, exercise not use Math.sqrt() or Math.pow().
- Given the positions and masses of a sequence of objects, write a plan to compute their center-of-mass or centroid. The centroid is the average position of the n objects, weighted by mass. If the positions and masses are given by (xi , yi , mi ), then the centroid (x, y, k) is given past:
grand = g1 + m2 + ... + mn 10 = (chiliad1x1 + ... + 1000north10north ) / m y = (money1 + ... + knynorthward ) / 1000
Write a program Centroid.java that reads in a sequence of positions and masses (xi , yi , chiliadi ) from standard input and prints out their middle of mass (x, y, m). Hint: model your plan after Boilerplate.java.
- Write a program Checkerboard.java that takes a command-line argument n and plots an n-by-n checkerboard with ruddy and blackness squares. Color the lower-left square carmine.
- Write a plan Rose.java that takes a control-line statement north and plots a rose with n petals (if north is odd) or 2n petals (if n is even) by plotting the polar coordinates (r, θ) of the function r = sin(n × θ) for θ ranging from 0 to 2π radians. Below is the desired output for north = iv, 7, and 8.
- Write a program Banner.coffee that takes a string s from the command line and brandish it in banner fashion on the screen, moving from left to correct and wrapping back to the showtime of the cord as the end is reached. Add a second command-line statement to control the speed.
- Write a program Circles.java that draws filled circles of random size at random positions in the unit square, producing images like those below. Your program should have four command-line arguments: the number of circles, the probability that each circle is blackness, the minimum radius, and the maximum radius.
Creative Exercises
- Spirographs. Write a program Spirograph.java that takes three command-line arguments R, r, and a and draws the resulting spirograph. A spirograph (technically, an epicycloid) is a curve formed by rolling a circle of radius r around a larger fixed circle or radius R. If the pen offset from the center of the rolling circle is (r+a), then the equation of the resulting curve at time t is given by
x(t) = (R+r)*cos(t) - (r+a)*cos(((R+r)/r)*t) y(t) = (R+r)*sin(t) - (r+a)*sin(((R+r)/r)*t)
Such curves were popularized by a best-selling toy that contains discs with gear teeth on the edges and pocket-sized holes that you could put a pen in to trace spirographs.
For a dramatic 3d effect, describe a circular image, e.k., globe.gif instead of a dot, and evidence it rotating over time. Hither'southward a movie of the resulting spirograph when R = 180, r = 40, and a = 15.
- Clock. Write a program Clock.coffee that displays an animation of the second, minute, and hour hands of an analog clock. Use the method StdDraw.show(1000) to update the display roughly once per second.
Hint: this may be one of the rare times when you desire to use the % operator with a double - it works the way you would expect.
- Oscilloscope. Write a program Oscilloscope.coffee to simulate the output of an oscilloscope and produce Lissajous patterns. These patterns are named after the French physicist, Jules A. Lissajous, who studied the patterns that arise when ii mutually perpendicular periodic disturbances occur simultaneously. Presume that the inputs are sinusoidal, and then tha the following parametric equations describe the curve:
x = Ax sin (wxt + θx) y = Ay sin (wyt + θy) Ax, Ay = amplitudes wx, westwardy = athwart velocity θx, θy = stage factors
Take the six parameters Ax, west10, θx, θy, westwardy, and θy from the command line.
For case, the first image below has Ax = Ay = one, wx = 2, westy = 3, θ10 = 20 degrees, θy = 45 degrees. The other has parameters (1, one, 5, iii, 30, 45)
Spider web Exercises
- Word and line count. Change WordCount.java and then that reads in text from standard input and prints out the number of characters, words, and lines in the text.
- Rainfall trouble. Write a plan Rainfall.java that reads in nonnegative integers (representing rainfall) one at a time until 999999 is entered, and so prints out the average of value (not including 999999).
- Remove duplicates. Write a program Duplicates.java that reads in a sequence of integers and prints back out the integers, except that information technology removes repeated values if they appear consecutively. For example, if the input is ane 2 2 one 5 i 1 7 seven 7 vii 1 1, your program should print out 1 2 one 5 1 vii 1.
- Run length encoding. Write a plan RunLengthEncoder.java that encodes a binary input using run length encoding. Write a plan RunLengthDecoder.java that decodes a run length encoded message.
- Head and tail. Write programs Head.coffee and Tail.coffee that take an integer command line input Northward and impress out the first or final North lines of the given file. (Impress the whole file if it consists of <= N lines of text.)
- Impress a random word. Read a list of Due north words from standard input, where N is unknown ahead of time, and print out one of the N words uniformly at random. Do not store the word list. Instead, employ Knuth's method: when reading in the ith word, select it with probability 1/i to be the selected word, replacing the previous champion. Print out the discussion that survives after reading in all of the information.
- Caesar cipher. Julius Caesar sent hole-and-corner messages to Cicero using a scheme that is now known as a Caesar cipher. Each letter is replaced past the letter k positions ahead of it in the alphabet (and yous wrap effectually if needed). The tabular array below gives the Caesar goose egg when thou = 3.
Original: A B C D Eastward F G H I J K Fifty Yard N O P Q R South T U 5 W Ten Y Z Caesar: D Eastward F G H I J K L M N O P Q R Due south T U V Westward X Y Z A B C
For example the message "VENI, VIDI, VICI" is converted to "YHQL, YLGL, YLFL". Write a programme Caesar.java that takes a command-line statement k and applies a Caesar cipher with shift = k to a sequence of letters read from standard input. If a letter is non an uppercase letter, but print it back out.
- Caesar nothing decoding. How would y'all decode a bulletin encrypted using a Caesar cipher? Hint: you should not need to write any more than lawmaking.
- Parity check. A Boolean matrix has the parity holding when each row and each column has an even sum. This is a simple type of error-correcting code because if one bit is corrupted in transmission (fleck is flipped from 0 to 1 or from i to 0) it tin exist detected and repaired. Here'south a 4 x four input file which has the parity holding:
1 0 one 0 0 0 0 0 1 one ane 1 0 ane 0 i
Write a program ParityCheck.coffee that takes an integer N as a command line input and reads in an N-by-N Boolean matrix from standard input, and outputs if (i) the matrix has the parity holding, or (2) indicates which single corrupted bit (i, j) can be flipped to restore the parity property, or (iii) indicates that the matrix was corrupted (more than ii $.25 would need to exist changed to restore the parity property). Apply as petty internal storage as possible. Hint: you practice not fifty-fifty take to store the matrix!
- Takagi's role. Plot Takagi'south function: everywhere continuous, nowhere differentiable.
- Hitchhiker problem. Y'all are interviewing N candidates for the sole position of American Idol. Every infinitesimal yous become to run into a new candidate, and you have one minute to decide whether or not to declare that person the American Idol. You may not alter your mind once you cease interviewing the candidate. Suppose that you tin can immediately rate each candidate with a single real number between 0 and 1, but of course, you don't know the rating of the candidates not even so seen. Devise a strategy and write a programme AmericanIdol that has at least a 25% take chances of picking the best candidate (assuming the candidates arrive in random lodge), reading the 500 information values from standard input.
Solution: interview for N/2 minutes and record the rating of the best candidate seen so far. In the next Due north/two minutes, selection the commencement candidate that has a college rating than the recorded one. This yields at least a 25% chance since you volition get the all-time candidate if the 2d best candidate arrives in the first Due north/ii minutes, and the best candidate arrives in the final N/2 minutes. This tin be improved slightly to 1/e = 0.36788 by using essentially the same strategy, simply switching over at time Due north/e.
- Nested diamonds. Write a program Diamonds.java that takes a control line input N and plots N nested squares and diamonds. Below is the desired output for N = three, 4, and five.
- Regular polygons. Create a function to plot an N-gon, centered on (x, y) of size length s. Use the function to draws nested polygons like the picture show beneath.
- Jutting squares. Write a programme BulgingSquares.coffee that draws the following optical illusion from Akiyoshi Kitaoka The center appears to bulge outwards fifty-fifty though all squares are the same size.
- Spiraling mice. Suppose that North mice that start on the vertices of a regular polygon with N sides, and they each head toward the nearest other mouse (in counterclockwise management) until they all meet. Write a plan to depict the logarithmic spiral paths that they trace out by drawing nested N-gons, rotated and shrunk as in this animation.
- Spiral. Write a program to draw a spiral like the one below.
- World. Write a program World.java that takes a real command-line statement α and plots a globe-like blueprint with parameter α. Plot the polar coordinates (r, θ) of the function f(θ) = cos(α × θ) for θ ranging from 0 to 7200 degrees. Below is the desired output for α = 0.8, 0.9, and 0.95.
- Cartoon strings. Write a plan RandomText.java that takes a string s and an integer North equally control line inputs, and writes the string N times at a random location, and in a random color.
- 2D random walk. Write a program RandomWalk.java to simulate a 2d random walk and animate the results. Start at the center of a 2N-by-2N filigree. The current location is displayed in blue; the trail in white.
- Rotating table. You lot are seated at a rotating foursquare tabular array (similar a lazy Susan), and at that place are four coins placed in the four corners of the table. Your goal is to flip the coins so that they are either all heads or all tails, at which bespeak a bong rings to notify you that you are washed. Y'all may select any two of them, make up one's mind their orientation, and (optionally) flip either or both of them over. To make things challenging, you lot are blindfolded, and the tabular array is spun after each fourth dimension you select 2 coins. Write a program RotatingTable.coffee that initializes the coins to random orientations. So, information technology prompts the user to select two positions (1-4), and identifies the orientation of each coin. Next, the user tin specify which, if any of the two coins to flip. The process repeats until the user solves the puzzle.
- Rotating table solver. Write another program RotatingTableSolver.java to solve the rotating table puzzle. One constructive strategy is to choose two coins at random and flip them to heads. However, if you get really unlucky, this could take an arbitrary number of steps. Goal: devise a strategy that always solves the puzzle in at most 5 steps.
- Hex. Hex is a 2-player board game popularized by John Nash while a graduate student at Princeton University, and afterwards commercialized past Parker Brothers. It is played on a hexagonal grid in the shape of an 11-past-eleven diamond. Write a program Hex.java that draws the board.
- Projectile motion with drag. Write a program BallisticMotion.java that plots the trajectory of a brawl that is shot with velocity v at an angle theta. Business relationship for gravitational and drag forces. Presume that the drag force is proportional to the foursquare of the velocity. Using Newton's equations of motions and the Euler-Cromer method, update the position, velocity, and dispatch according to the following equations:
five = sqrt(vx*vx + vy*vy) ax = - C * 5 * vx ay = -G - C * v * vy vx = vx + ax * dt vy = vy + ay * dt ten = ten + vx * dt y = y + vy * dt
Apply G = 9.8, C = 0.002, and set up the initial velocity to 180 and the angle to sixty degrees.
- Heart. Write a programme Heart.java to describe a pink center: Draw a diamond, then draw two circles to the upper left and upper right sides.
- Irresolute foursquare. Write a program that draws a square and changes its colour each 2d.
- Simple harmonic motion. Repeat the previous exercise, merely animate the Lissajous patterns as in this applet. Ex: A = B = due westten = wy = 1, but at each time t draw 100 (or so) points with φ10 ranging from 0 to 720 degrees, and φx ranging from 0 to 1080 degrees.
- Bresenham's line cartoon algorithm. To plot a line segment from (x1, y1) to (x2, y2) on a monitor, say 1024-by-1024, you demand to make a discrete approximation to the continuous line and determine exactly which pixels to plough on. Bresenham's line drawing algorithm is a clever solution that works when the slope is betwixt 0 and 1 and x1 < x2.
int dx = x2 - x1; int dy = y2 - y1; int y = y1; int eps = 0; for (int x = x1; x <= x2; ten++) { StdDraw.point(ten, y); eps += dy; if (2*eps >= dx) { y++; eps -= dx; } }
- Modify Bresenham's algorithm to handle arbitrary line segments.
- Miller'due south madness. Write a plan Madness.coffee to plot the parametric equation:
10 = sin(0.99 t) - 0.seven cos( 3.01 t) y = cos(i.01 t) + 0.i sin(15.03 t)
- Fay's butterfly. Write a plan Butterfly.java to plot the polar equation:
r = e^(cos t) - ii cos(4t) + (sin(t/12)^five)
- Student database. The file students.txt contains a listing of students enrolled in an introductory computer science class at Princeton. The first line contains an integer N that specifies the number of students in the database. Each of the next N lines consists of four pieces of information, separated by whitespace: first name, last name, email address, and section number. The program Students.java reads in the integer Northward and and then N lines of information of standard input, stores the data in four parallel arrays (an integer array for the section number and string arrays for the other fields). Then, the programme prints out a list of students in section 4 and v.
- Shuffling. In the October vii, 2003 California state runoff election for governor, at that place were 135 official candidates. To avoid the natural prejudice against candidates whose names appear at the end of the alphabet (Jon W. Zellhoefer), California election officials sought to guild the candidates in random gild. Write a program programme Shuffle.java that takes a command-line argument N, reads in N strings from standard input, and prints them back out in shuffled order. (California decided to randomize the alphabet instead of shuffling the candidates. Using this strategy, not all N! possible outcomes are equally likely or even possible! For example, ii candidates with very similar last names will always end up next to each other.)
- Reverse. Write a program Reverse.java that reads in an arbitrary number of real values from standard input and prints them in reverse order.
- Time series analysis. This problem investigates two methods for forecasting in time serial assay. Moving average or exponential smoothing.
- Polar plots. Create whatsoever of these polar plots.
- Coffee games. Utilise StdDraw.java to implement one of the games at javaunlimited.internet.
- Consider the following programme.
public class Mystery { public static void chief(String[] args) { int N = Integer.parseInt(args[0]); int[] a = new int[Grand]; while(!StdIn.isEmpty()) { int num = StdIn.readInt(); a[num]++; } for (int i = 0; i < Yard; i++) for (int j = 0; j < a[i]; j++) System.out.print(i + " "); Organisation.out.println(); } }
Suppose the file input.txt contains the following integers:
8 8 3 5 i vii 0 9 2 6 9 7 iv 0 5 3 ix 3 7 6
What is the contents of the array a after running the post-obit command
java Mystery 10 < input.txt
- Loftier-low. Shuffle a deck of cards, and deal i to the player. Prompt the player to guess whether the next carte is college or lower than the current menu. Echo until histrion guesses information technology wrong. Game bear witness: ???? used this.
- Elastic collisions. Write a program CollidingBalls.java that takes a command-line argument due north and plots the trajectories of n billowy assurance that bounce of the walls and each other co-ordinate to the laws of elastic collisions. Assume all the balls have the same mass.
- Elastic collisions with obstacles. Each brawl should have its own mass. Put a large brawl in the center with zero initial velocity. Brownian motion.
- Statistical outliers. Modify Boilerplate.coffee to impress out all the values that are larger than 1.5 standard deviations from the mean. Yous volition need an array to store the values.
- Optical illusions. Create a Kofka ring or one of the other optical illusions collected by Edward Adelson.
- Computer animation. In 1995 James Gosling presented a demonstration of Java to Sun executives, illustrating its potential to evangelize dynamic and interactive Web content. At the time, web pages were fixed and non-interactive. To demonstrate what the Web could be, Gosling presented applets to rotate 3D molecules, visualize sorting routines, and Duke cart-wheeling across the screen. Java was officially introduced in May 1995 and widely adopted in the engineering sector. The Cyberspace would never be the same.
- Cart-wheeling Duke. Modify Duke.java and so that it cartwheels 5 times across the screen, from right to left, wrapping around when it hits the window boundary. Repeat this cart-wheeling bike 100 times. Hint: later on displaying a sequence of 17 frames, motility 57 pixels to the left and repeat. Proper name your program MoreDuke.java.
- Tac (cat backwards). Write a plan Tac.java that reads lines of text from standard input and prints the lines out in opposite club.
- Game. Implement the game contrivance using StdDraw: move a blue disc inside the unit foursquare to affect a randomly placed green disc, while avoiding the moving red discs. Later on each touch, add a new moving carmine disc.
- Uncomplicated harmonic move. Create an animation similar the one below from Wikipedia of simple harmonic motion.
- Yin yang. Draw a yin yang using StdDraw.arc().
- 20 questions. Write a program QuestionsTwenty.coffee that plays twenty questions from the reverse indicate of view: the user thinks of a number between 1 and a million and the computer makes the guesses. Use binary search to ensure that the figurer needs at virtually 20 guesses.
- Write a program DeleteX.java that reads in text from standard input and deletes all occurrences of the letter X. To filter a file and remove all X'south, run your program with the following command:
% coffee DeleteX < input.txt > output.txt
- Write a program ThreeLargest.coffee that reads integers from standard input and prints out the 3 largest inputs.
- Write a plan Pnorm.java that takes a command-line statement p, reads in existent numbers from standard input, and prints out their p-norm. The p-norm norm of a vector (x1, ..., xNorthward) is defined to be the pth root of (|10one|p + |x2|p + ... + |xN|p).
- Consider the following Java program.
public class Mystery { public static void main(Cord[] args) { int i = StdIn.readInt(); int j = StdIn.readInt(); Arrangement.out.println((i-one)); Arrangement.out.println((j*i)); } }
Suppose that the file input.txt contains
- Repeat the previous exercise but apply the following control instead
java Mystery < input.txt | java Mystery | coffee Mystery | coffee Mystery
- Consider the following Java program.
public class Mystery { public static void master(String[] args) { int i = StdIn.readInt(); int j = StdIn.readInt(); int k = i + j; System.out.println(j); System.out.println(k); } }
Suppose that the file input.txt contains the integers 1 and 1. What does the following control practice?
java Mystery < input.txt | java Mystery | coffee Mystery | java Mystery
- Consider the Java programme Ruler.java.
public course Ruler { public static void main(String[] args) { int n = StdIn.readInt(); Cord s = StdIn.readString(); System.out.println((north+1) + " " + s + (n+i) + s); } }
Suppose that the file input.txt contains the integers ane and 1. What does the post-obit command do?
java Ruler < input.txt | coffee Ruler | java Ruler | java Ruler
- Change Add.java so that it re-asks the user to enter two positive integers if the user types in a non-positive integer.
- Change TwentyQuestions.java so that it re-asks the user to enter a response if the user types in something other than true or simulated. Hint: add a do-while loop within the main loop.
- Nonagram. Write a plan to plot a nonagram.
- Star polygons. Write a program StarPolygon.java that takes two control line inputs p and q, and plots the {p/q}-star polygon.
- Complete graph. Write a program to plot that takes an integer Due north, plots an Due north-gon, where each vertex lies on a circle of radius 256. So draw a gray line connecting each pair of vertices.
- Necker cube. Write a program NeckerCube.java to plot a Necker cube.
- What happens if you move the StdDraw.clear(Colour.Black) command to before the showtime of the while loop in BouncingBall.coffee? Respond: endeavour it and observe a nice woven 3d pattern with the given starting velocity and position.
- What happens if you lot change the parameter of StdDraw.show() to 0 or yard in BouncingBall.java?
- Write a program to plot a circular ring of width 10 like the i beneath using two calls to StdDraw.filledCircle().
- Write a plan to plot a circular band of width x similar the one below using a nested for loop and many calls to StdDraw.point().
- Write a program to plot the Olympic rings.
- Write a programme BouncingBallDeluxe.java that embellishes BouncingBall.coffee by playing a sound effect upon collision with the wall using StdAudio and the audio file pipebang.wav.
Source: https://introcs.cs.princeton.edu/java/15inout/
0 Response to "Write Programs That Read a Line of Input as a String and Print Only the Uppercase Letters"
Post a Comment