How to Read Commands From Keyboard Java for Game

1.5   Input and Output

In this section we extend the fix of simple abstractions (command-line input and standard output) that we take been using as the interface betwixt our Java programs and the outside world to include standard input, standard cartoon, and standard audio. Standard input makes it convenient for us to write programs that procedure arbitrary amounts of input and to interact with our programs; standard describe makes information technology possible for us to work with graphics; and standard sound adds audio. Bird's eye view

Bird'southward-centre view.

A Java program takes input values from the command line and prints a cord of characters every bit output. By default, both command-line arguments and standard output are associated with an awarding that takes commands, which we refer to as the terminal window.

  • Control-line arguments. All of our classes have a main() method that takes a String assortment args[] as statement. That array is the sequence of command-line arguments that we type. If nosotros intend for an argument to be a number, we must employ a method such as Integer.parseInt() to convert information technology from String to the appropriate type.
  • Standard output. To print output values in our programs, we have been using System.out.println(). Java sends the results to an abstruse stream of characters known every bit standard output. By default, the operating system connects standard output to the terminal window. All of the output in our programs and then far has been appearing in the final window.

RandomSeq.java uses this model: It takes a command-line argument northward and prints to standard output a sequence of n random numbers between 0 and i.

To complete our programming model, we add the following libraries:

  • Standard input. Read numbers and strings from the user.
  • Standard drawing. Plot graphics.
  • Standard audio. Create sound.

Standard output.

Java'due south

Organization.out.print()

and

Organization.out.println()

methods implement the basic standard output abstraction that nosotros demand. Nevertheless, to care for standard input and standard output in a uniform manner (and to provide a few technical improvements), we apply like methods that are defined in our StdOut library:

Standard output API

Coffee'southward

impress()

and

println()

methods are the ones that you have been using. The

printf()

method gives the states more control over the appearance of the output.

  • Formatted printing basics. In its simplest form, printf() takes two arguments. The offset argument is chosen the format string. It contains a conversion specification that describes how the second statement is to exist converted to a string for output.
    anatomy of printf() call
    Format strings begin with % and end with a one-letter conversion code. The following table summarizes the most frequently used codes:
    formatting examples for printf()
  • Format string. The format string can contain characters in addition to those for the conversion specification. The conversion specification is replaced past the statement value (converted to a string as specified) and all remaining characters are passed through to the output.
  • Multiple arguments. The printf() function can take more than 2 arguments. In this case, the format string will have an additional 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 string or a value from one of Java'south archaic types. One of the key features of the standard input stream is that your program consumes values when it reads them. One time your plan has read a value, information technology cannot dorsum up and read it again. The library is defined past the following API:

Standard input API

We now consider several examples in item.

  • Typing input. When you use the java command to invoke a Java plan from the command line, y'all actually are doing three things: (1) issuing a command to start executing your program, (2) specifying the values of the command-line arguments, and (3) first to define the standard input stream. The string of characters that you type in the terminal window after the control line is the standard input stream. For example, AddInts.java takes a command-line argument due north, then reads north numbers from standard input and adds them, and prints the result to standard output:
    anatomy of a command
  • Input format. If you type abc or 12.2 or true when StdIn.readInt() is expecting an int, then information technology will respond with an InputMismatchException. StdIn treats strings of sequent whitespace characters as identical to 1 infinite and allows yous to delimit your numbers with such strings.
  • Interactive user input. TwentyQuestions.java is a simple example of a program that interacts with its user. The plan generates a random integer and so gives clues to a user trying to guess the number. The fundamental difference between this program and others that nosotros have written is that the user has the power to change the control period 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 there is no restriction of the size of the input stream. Boilerplate.java reads in a sequence of real numbers from standard input and prints their average.

Redirection and piping.

For many applications, typing input data equally a standard input stream from the terminal window is untenable because doing so limits our program's processing power past the amount of data that nosotros can type. Similarly, we often desire to salve the information printed on the standard output stream for later use. We can apply operating system mechanisms to address both issues.

  • Redirecting standard output to a file. By adding a elementary directive to the command that invokes a plan, we can redirect its standard output to a file, either for permanent storage or for input to some other plan at a later on time. For example, the command
    Redirecting standard output
    specifies that the standard output stream is non to exist printed in the last window, but instead is to exist written to a text file named data.txt. Each call to StdOut.print() or StdOut.println() appends text at the finish of that file. In this example, the end result is a file that contains 1,000 random values.
  • Redirecting standard output from a file. Similarly, nosotros tin can redirect standard input so that StdIn reads data from a file instead of the terminal window. For example, the control
    Redirecting standard input
    reads a sequence of numbers from the file information.txt and computes their average value. Specifically, the < symbol is a directive to implement the standard input stream by reading from the file information.txt instead of by waiting for the user to type something into the terminal window. When the program calls StdIn.readDouble(), the operating system reads the value from the file. This facility to redirect standard input from a file enables united states to process huge amounts of data from whatever source with our programs, limited only by the size of the files that we tin store.
  • Connecting two programs. The most flexible way to implement the standard input and standard output abstractions is to specify that they are implemented by our ain programs! This mechanism is chosen piping. For example, the post-obit command
    Piping
    specifies that the standard output for RandomSeq and the standard input stream for Boilerplate are the same stream.
  • Filters. For many common tasks, information technology is convenient to think of each programme as a filter that converts a standard input stream to a standard output stream in some way, RangeFilter.coffee takes ii control-line arguments and prints on standard output those numbers from standard input that fall within the specified range.

    Your operating arrangement too provides a number of filters. For example, 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                
    Another useful filter is more, which reads data from standard input and displays it in your terminal window one screenful at a fourth dimension. For example, if yous type
    %                  java RandomSeq grand | more                
    you will come across as many numbers as fit in your terminal window, but more will wait for you to hit the space bar before displaying each succeeding screenful.

Standard cartoon.

Now we introduce a simple abstraction for producing drawings as output. Nosotros imagine an abstract drawing device capable of drawing lines and points on a two-dimensional sheet. 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 two kinds of methods: cartoon commands that crusade the device to take an action (such as cartoon a line or cartoon a betoken) and control commands that set parameters such as the pen size or the coordinate scales.

  • Basic drawing commands. We beginning consider the drawing commands:
    Standard drawing API: drawing commands
    These methods are nearly self-documenting: StdDraw.line(x0, y0, x1, y1) draws a straight line segment connecting the point (x 0, y 0) with the bespeak (x i, y ane). StdDraw.signal(10, y) draws a spot centered on the point (x, y). The default coordinate scale is the unit square (all x- and y-coordinates betwixt 0 and 1). The standard implementation displays the canvas in a window on your figurer's screen, with blackness lines and points on a white background.

    Your first cartoon. The HelloWorld for graphics programming with StdDraw is to depict a triangle with a signal within. Triangle.coffee accomplishes this with three calls to StdDraw.line() and one phone call to StdDraw.point().

  • Command commands. The default canvas size is 512-past-512 pixels and the default coordinate system is the unit foursquare, but we often want to draw plots at different scales. Also, we often want to draw line segments of different thickness or points of different size from the standard. To conform these needs, StdDraw has the following methods:
    Standard drawing API: control commands
    For example, the two-call sequence
    StdDraw.setXscale(x0, x1); StdDraw.setYscale(y0, y1);                
    sets the drawing coordinates to exist within a bounding box whose lower-left corner is at (x 0, y 0) and whose upper-correct corner is at (x ane, y 1).
    • Filtering data to a standard drawing. PlotFilter.coffee reads a sequence of points divers by (10, y) coordinates from standard input and draws a spot at each point. It adopts the convention that the first four numbers on standard input specify the bounding box, so that it can scale the plot.
      % java PlotFilter < USA.txt

      13509 cities in the US

    • Plotting a part graph. FunctionGraph.java plots the function y = sin(ivx) + sin(2010) in the interval (0, π). In that location are an infinite number of points in the interval, so we have to brand practise with evaluating the function at a finite number of points within the interval. We sample the function past choosing a set of 10-values, then calculating y-values by evaluating the role at each x-value. Plotting the function by connecting successive points with lines produces what is known equally a piecewise linear approximation.
      Plotting a function graph
  • Outline and filled shapes. StdDraw besides includes methods to draw circles, rectangles, and arbitrary polygons. Each shape defines an outline. When the method proper name is just the shape proper name, that outline is traced past the drawing pen. When the method name begins with filled, the named shape is instead filled solid, non traced.
    Standard drawing API: shapes
    The arguments for circumvolve() ascertain a circumvolve of radius r; the arguments for square() define a square of side length 2r centered on the given point; and the arguments for polygon() ascertain a sequence of points that we connect by lines, including one from the last point to the start point.
    Standard drawing shapes
  • 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.
    Standard drawing text and color commands
    In this code, java.awt.Font and java.awt.Color are abstractions that are implemented with non-primitive types that you volition learn virtually in Section three.ane. Until and so, we get out the details to StdDraw. The default ink color is blackness; the default font is a 16-point plain Serif font.
  • Double buffering. StdDraw supports a powerful calculator graphics feature known as double buffering. When double buffering is enabled past calling enableDoubleBuffering(), all drawing takes place on the offscreen sail. The offscreen canvas is non displayed; it exists only in computer retention. But when you phone call show() does your drawing get copied from the offscreen sheet to the onscreen sheet, where it is displayed in the standard cartoon window. You can retrieve of double buffering as collecting all of the lines, points, shapes, and text that y'all tell it to draw, and then cartoon them all simultaneously, upon request. One reason to utilize double buffering is for efficiency when performing a large number of cartoon commands.
  • Estimator animations. Our most important employ of double buffering is to produce computer animations, where we create the illusion of motility by rapidly displaying static drawings. We can produce animations by repeating the following four steps:
    • Clear the offscreen sheet.
    • Draw objects on the offscreen
    • Copy the offscreen canvas to the onscreen canvas.
    • Look for a short while.

    In back up of these steps, the StdDraw has several methods:

    Standard drawing animation commands

    The "Hello, World" program for animation is to produce a black brawl that appears to motility around on the canvas, billowy off the purlieus according to the laws of elastic collision. Suppose that the ball is at position (x, y) and nosotros want to create the impression of having it motility to a new position, say (x + 0.01, y + 0.02). We exercise and then in 4 steps:

    • Clear the offscreen canvas to white.
    • Draw a black ball at the new position on the offscreen canvas.
    • Copy the offscreen sheet to the onscreen canvas.
    • Wait for a curt while.

    To create the illusion of movement, BouncingBall.java iterates these steps for a whole sequence of positions of the ball.

    Bouncing ball
  • Images. Our standard draw library supports cartoon pictures too equally geometric shapes. The command StdDraw.flick(x, y, filename) plots the image in the given filename (either JPEG, GIF, or PNG format) on the canvas, centered on (x, y). BouncingBallDeluxe.coffee illustrates an example where the bouncing brawl is replaced by an image of a tennis ball.
  • User interaction. Our standard draw library also includes methods so that the user tin interact with the window using the mouse.
    double mouseX()          render x-coordinate of mouse double mouseY()          return y-coordinate of mouse boolean mousePressed()   is the mouse currently being pressed?                
    • A offset example. MouseFollower.java is the HelloWorld of mouse interaction. It draws a bluish ball, centered on the location of the mouse. When the user holds downward the mouse button, the ball changes color from bluish to cyan.
    • A simple attractor. OneSimpleAttractor.coffee simulates the move of a blue ball that is attracted to the mouse. It also accounts for a drag strength.
    • Many simple attractors. SimpleAttractors.java simulates the movement of 20 blue assurance that are attracted to the mouse. Information technology also accounts for a elevate force. When the user clicks, the balls disperse randomly.
    • Springs. Springs.java implements a spring organization.

Standard audio.

StdAudio is a library that you lot can employ to play and manipulate audio files. Information technology allows you to play, dispense and synthesize audio.

Standard audio API

We innovate some some basic concepts backside one of the oldest and most important areas of computer science and scientific calculating: digital indicate processing.

  • Concert A. Concert A is a sine wave, scaled to oscillate at a frequency of 440 times per second. The function sin(t) repeats itself once every 2π units on the ten-axis, and so if we measure t in seconds and plot the function sin(2πt × 440) we go a curve that oscillates 440 times per second. The amplitude (y-value) corresponds to the book. We assume information technology is scaled to exist between −i and +1.
  • Other notes. A unproblematic mathematical formula characterizes the other notes on the chromatic scale. They are divided equally on a logarithmic (base 2) scale: there are twelve notes on the chromatic calibration, and we go the ith annotation above a given annotation by multiplying its frequency past the (i/12)thursday power of 2.
    Musical notes, numbers, and waves
    When you double or halve the frequency, you move upwards or down an octave on the calibration. For case 880 hertz is one octave above concert A and 110 hertz is two octaves below concert A.
  • Sampling. For digital sound, we correspond a bend past sampling it at regular intervals, in precisely the same manner as when nosotros plot function graphs. We sample sufficiently often that nosotros have an authentic representation of the curve—a widely used sampling charge per unit is 44,100 samples per second. Information technology is that unproblematic: we represent sound every bit an array of numbers (real numbers that are between −1 and +1).
    For instance, the post-obit code fragment plays concert A for 10 seconds.
    int SAMPLING_RATE = 44100; double hz = 440.0; double elapsing = 10.0; int north = (int) (SAMPLING_RATE * elapsing); double[] a = new double[northward+1]; for (int i = 0; i <= due north; i++) {    a[i] = Math.sin(two * Math.PI * i * hz / SAMPLING_RATE);  } StdAudio.play(a);                
  • Play that tune. PlayThatTune.java is an example that shows how easily we 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

  1. Write a programme MaxMin.java that reads in integers (equally many as the user enters) from standard input and prints out the maximum and minimum values.
  2. Write a programme Stats.coffee that takes an integer command-line argument n, reads n floating-point numbers from standard input, and prints their mean (average value) and sample standard deviation (square root of the sum of the squares of their differences from the average, divided by north−1).
  3. Write a program LongestRun.coffee that reads in a sequence of integers and prints out both the integer that appears in a longest sequent run and the length of the run. For instance, if the input is 1 2 ii 1 5 1 one 7 7 seven 7 ane 1, and then your program should print Longest run: 4 consecutive 7s.
  4. 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 do, a word is a sequence of non-whitespace characters that is surrounded by whitespace.
  5. Write a programme Closest.java that takes three floating-point command-line arguments \(x, y, z\), reads from standard input a sequence of bespeak coordinates \((x_i, y_i, z_i)\), and prints the coordinates of the signal closest to \((x, y, z)\). Recall that the square of the distance between \((x, y, z)\) and \((x_i, y_i, z_i)\) is \((ten - x_i)^2 + (y - y_i)^2 + (z - z_i)^2\). For efficiency, do not use Math.sqrt() or Math.pow().
  6. Given the positions and masses of a sequence of objects, write a program 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 past (xi , yi , one thousandi ), then the centroid (ten, y, k) is given past:
    m  =                  mi                                    +                  mii                                    + ... +                  gn                                    x  = (mix1                                    +  ... +                  mnxnorth                  ) / m y  = (yard1yone                                    +  ... +                  mnynorth                  ) / g                

    Write a program Centroid.java that reads in a sequence of positions and masses (10i , yi , mi ) from standard input and prints out their center of mass (x, y, thousand). Hint: model your programme after Average.coffee.

  7. Write a program Checkerboard.java that takes a command-line statement n and plots an n-by-n checkerboard with red and black squares. Color the lower-left square red.
  8. Write a plan Rose.java that takes a command-line argument n and plots a rose with n petals (if n is odd) or 2n petals (if northward is even) past plotting the polar coordinates (r, θ) of the function r = sin(n × θ) for θ ranging from 0 to 2π radians. Below is the desired output for n = iv, 7, and 8.

    rose

  9. Write a programme Banner.coffee that takes a cord southward from the command line and display it in banner fashion on the screen, moving from left to right and wrapping back to the beginning of the string as the end is reached. Add a second command-line argument to command the speed.
  10. 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 control-line arguments: the number of circles, the probability that each circle is black, the minimum radius, and the maximum radius.
    random circles

Creative Exercises

  1. Spirographs. Write a plan Spirograph.java that takes three control-line arguments R, r, and a and draws the resulting spirograph. A spirograph (technically, an epicycloid) is a bend formed past rolling a circle of radius r around a larger fixed circle or radius R. If the pen offset from the heart of the rolling circle is (r+a), and then the equation of the resulting curve at time t is given by
    10(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 minor holes that you could put a pen in to trace spirographs.

    For a dramatic 3d effect, draw a circular paradigm, e.grand., earth.gif instead of a dot, and show information technology rotating over time. Here's a film of the resulting spirograph when R = 180, r = 40, and a = 15.

  2. Clock. Write a program Clock.java that displays an animation of the second, minute, and 60 minutes hands of an analog clock. Utilize the method StdDraw.show(m) to update the display roughly one time per second.

    Hint: this may be one of the rare times when you want to use the % operator with a double - it works the way you would await.

  3. Oscilloscope. Write a plan Oscilloscope.coffee to simulate the output of an oscilloscope and produce Lissajous patterns. These patterns are named subsequently the French physicist, Jules A. Lissajous, who studied the patterns that ascend when 2 mutually perpendicular periodic disturbances occur simultaneously. Presume that the inputs are sinusoidal, then tha the post-obit parametric equations describe the curve:
    x = Ax sin (wxt + θx) y = Ay sin (wyt + θy) Ax, Ay = amplitudes due west10, wy                  = angular velocity θx, θy                  = phase factors                

    Accept the six parameters Ax, westwardx, θx, θy, wy, and θy from the control line.

    For case, the offset paradigm below has Ax = Ay = one, westx = two, wy = 3, θten = 20 degrees, θy = 45 degrees. The other has parameters (1, 1, 5, three, 30, 45)

Web Exercises

  1. Word and line count. Alter WordCount.java so that reads in text from standard input and prints out the number of characters, words, and lines in the text.
  2. Rainfall problem. Write a programme Rainfall.java that reads in nonnegative integers (representing rainfall) one at a time until 999999 is entered, and then prints out the average of value (not including 999999).
  3. Remove duplicates. Write a programme Duplicates.java that reads in a sequence of integers and prints back out the integers, except that it removes repeated values if they appear consecutively. For example, if the input is 1 ii two 1 5 1 ane seven 7 7 seven i 1, your program should print out 1 2 i v ane vii 1.
  4. Run length encoding. Write a plan RunLengthEncoder.java that encodes a binary input using run length encoding. Write a program RunLengthDecoder.coffee that decodes a run length encoded message.
  5. Caput and tail. Write programs Head.java and Tail.java that take an integer command line input Northward and print out the first or last N lines of the given file. (Print the whole file if it consists of <= N lines of text.)
  6. Print a random discussion. Read a listing 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 discussion list. Instead, use Knuth's method: when reading in the ith word, select it with probability one/i to be the selected word, replacing the previous champion. Print out the discussion that survives after reading in all of the information.
  7. Caesar cipher. Julius Caesar sent secret messages to Cicero using a scheme that is at present known as a Caesar zilch. Each letter is replaced by the letter k positions ahead of it in the alphabet (and you wrap around if needed). The tabular array beneath gives the Caesar cipher when k = 3.
    Original:  A B C D Eastward F Chiliad H I J One thousand L M N O P Q R Due south T U V W X Y Z Caesar:    D E F G H I J K L M N O P Q R S T U V W 10 Y Z A B C                

    For example the message "VENI, VIDI, VICI" is converted to "YHQL, YLGL, YLFL". Write a programme Caesar.coffee that takes a command-line argument grand and applies a Caesar cipher with shift = m to a sequence of letters read from standard input. If a letter is not an uppercase letter, merely impress it back out.

  8. Caesar cipher decoding. How would yous decode a message encrypted using a Caesar cipher? Hint: you should non demand to write whatever more code.
  9. Parity check. A Boolean matrix has the parity property when each row and each column has an even sum. This is a elementary type of error-correcting code because if one bit is corrupted in manual (bit is flipped from 0 to one or from 1 to 0) it tin be detected and repaired. Hither's a four 10 iv input file which has the parity property:
    one 0 1 0 0 0 0 0 1 i ane 1 0 1 0 1                

    Write a program ParityCheck.java that takes an integer N equally a command line input and reads in an Northward-by-N Boolean matrix from standard input, and outputs if (i) the matrix has the parity property, or (ii) indicates which single corrupted bit (i, j) can be flipped to restore the parity holding, or (iii) indicates that the matrix was corrupted (more than two bits would need to be inverse to restore the parity property). Utilize equally niggling internal storage as possible. Hint: you do not even have to store the matrix!

  10. Takagi's function. Plot Takagi's function: everywhere continuous, nowhere differentiable.
  11. Hitchhiker problem. Yous are interviewing N candidates for the sole position of American Idol. Every minute you get to see a new candidate, and y'all have one infinitesimal to make up one's mind whether or not to declare that person the American Idol. You may not change your mind once you lot terminate interviewing the candidate. Suppose that you can immediately rate each candidate with a single real number between 0 and 1, but of grade, yous don't know the rating of the candidates not yet seen. Devise a strategy and write a program AmericanIdol that has at least a 25% adventure of picking the best candidate (assuming the candidates get in in random order), reading the 500 data values from standard input.

    Solution: interview for N/2 minutes and record the rating of the all-time candidate seen so far. In the next Due north/2 minutes, pick the first candidate that has a higher rating than the recorded one. This yields at to the lowest degree a 25% chance since y'all will get the best candidate if the 2d best candidate arrives in the first N/2 minutes, and the best candidate arrives in the terminal North/two minutes. This tin be improved slightly to i/eastward = 0.36788 past using substantially the same strategy, but switching over at time Northward/due east.

  12. Nested diamonds. Write a plan Diamonds.java that takes a control line input Northward and plots N nested squares and diamonds. Below is the desired output for N = three, 4, and 5.
  13. Regular polygons. Create a function to plot an North-gon, centered on (x, y) of size length south. Use the role to draws nested polygons like the pic below.
    nested polygons
  14. Bulging squares. Write a programme BulgingSquares.java that draws the following optical illusion from Akiyoshi Kitaoka The heart appears to bulge outwards even though all squares are the same size.
    bulging squares
  15. Spiraling mice. Suppose that N mice that offset on the vertices of a regular polygon with Due north sides, and they each caput toward the nearest other mouse (in counterclockwise management) until they all run across. Write a program to describe the logarithmic spiral paths that they trace out by drawing nested N-gons, rotated and shrunk as in this animation.
  16. Spiral. Write a program to draw a spiral like the one below.

    spiral

  17. Globe. Write a programme Globe.java that takes a existent command-line statement α and plots a globe-similar pattern 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.nine, and 0.95.
  18. Cartoon strings. Write a program RandomText.coffee that takes a string s and an integer Due north as command line inputs, and writes the string N times at a random location, and in a random color.
  19. 2nd random walk. Write a program RandomWalk.java to simulate a 2nd random walk and animate the results. Start at the center of a 2N-by-2N grid. The electric current location is displayed in blue; the trail in white.
    random walk in 2d after 5 steps random 2d walk after 25 steps random 2d walk after 106 steps
  20. Rotating table. Y'all are seated at a rotating square table (like a lazy Susan), and there are iv coins placed in the four corners of the tabular array. Your goal is to flip the coins so that they are either all heads or all tails, at which betoken a bell rings to notify y'all that you are washed. You may select any 2 of them, make up one's mind their orientation, and (optionally) flip either or both of them over. To make things challenging, you are blindfolded, and the table is spun later each time yous select 2 coins. Write a programme RotatingTable.java that initializes the coins to random orientations. Then, it prompts the user to select ii positions (i-4), and identifies the orientation of each money. Adjacent, the user can specify which, if whatsoever of the ii coins to flip. The process repeats until the user solves the puzzle.
  21. Rotating table solver. Write another program RotatingTableSolver.coffee to solve the rotating table puzzle. I effective strategy is to cull two coins at random and flip them to heads. Withal, if y'all get really unlucky, this could take an arbitrary number of steps. Goal: devise a strategy that always solves the puzzle in at virtually five steps.
  22. Hex. Hex is a two-player lath game popularized by John Nash while a graduate student at Princeton University, and later commercialized by Parker Brothers. Information technology is played on a hexagonal grid in the shape of an 11-by-xi diamond. Write a program Hex.coffee that draws the board.
  23. Projectile motion with drag. Write a program BallisticMotion.java that plots the trajectory of a ball that is shot with velocity v at an angle theta. Business relationship for gravitational and drag forces. Assume that the drag force is proportional to the square of the velocity. Using Newton's equations of motions and the Euler-Cromer method, update the position, velocity, and acceleration according to the following equations:
    v  = sqrt(vx*vx + vy*vy)  ax = - C * v * vx          ay = -G - C * five * vy vx = vx + ax * dt          vy = vy + ay * dt  x =  x + vx * dt           y =  y + vy * dt                

    Use G = ix.viii, C = 0.002, and set the initial velocity to 180 and the angle to lx degrees.

  24. Heart. Write a programme Eye.coffee to draw a pink eye: Draw a diamond, then draw two circles to the upper left and upper correct sides.
    Heart
  25. Changing foursquare. Write a program that draws a square and changes its color each second.
  26. Unproblematic harmonic motion. Repeat the previous exercise, simply animate the Lissajous patterns equally in this applet. Ex: A = B = wx = due westy = 1, just at each fourth dimension t depict 100 (or so) points with φx ranging from 0 to 720 degrees, and φx ranging from 0 to 1080 degrees.
  27. Bresenham's line drawing algorithm. To plot a line segment from (x1, y1) to (x2, y2) on a monitor, say 1024-by-1024, yous need to brand a discrete approximation to the continuous line and decide exactly which pixels to turn on. Bresenham'due south 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; x++) {     StdDraw.signal(x, y);     eps += dy;     if (two*eps >= dx)  {        y++;        eps -= dx;     } }                
  28. Modify Bresenham'southward algorithm to handle capricious line segments.
  29. Miller'due south madness. Write a program Madness.java to plot the parametric equation:
    x = sin(0.99 t) - 0.vii cos( 3.01 t) y = cos(ane.01 t) + 0.1 sin(xv.03 t)                
    where the parameter t is in radians. You should get the following complex picture. Experiment by changing the parameters and produce original pictures.
  30. Fay's butterfly. Write a program Butterfly.java to plot the polar equation:
    r = east^(cos t) - two cos(4t) + (sin(t/12)^5)                
    where the parameter t is in radians. You lot should get an image similar the following butterfly-like figure. Experiment by changing the parameters and produce original pictures.
    Butterfly
  31. Student database. The file students.txt contains a list of students enrolled in an introductory computer science class at Princeton. The get-go line contains an integer Due north 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, e-mail address, and department number. The program Students.java reads in the integer N and then N lines of data of standard input, stores the information in 4 parallel arrays (an integer array for the department number and cord arrays for the other fields). Then, the program prints out a list of students in section 4 and 5.
  32. Shuffling. In the October seven, 2003 California state runoff ballot for governor, there were 135 official candidates. To avoid the natural prejudice against candidates whose names appear at the end of the alphabet (Jon W. Zellhoefer), California ballot officials sought to guild the candidates in random order. Write a program plan Shuffle.java that takes a control-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 Northward! possible outcomes are equally probable or even possible! For example, two candidates with very similar final names volition ever end up next to each other.)
  33. Reverse. Write a program Reverse.coffee that reads in an capricious number of real values from standard input and prints them in opposite order.
  34. Fourth dimension series analysis. This trouble investigates two methods for forecasting in time serial analysis. Moving average or exponential smoothing.
  35. Polar plots. Create whatever of these polar plots.
  36. Coffee games. Use StdDraw.java to implement one of the games at javaunlimited.cyberspace.
  37. Consider the following program.
    public class Mystery {    public static void main(String[] args) {       int N = Integer.parseInt(args[0]);       int[] a = new int[M];        while(!StdIn.isEmpty()) {          int num = StdIn.readInt();          a[num]++;       }        for (int i = 0; i < Thousand; i++)          for (int j = 0; j < a[i]; j++)             System.out.print(i + " ");       Arrangement.out.println();    } }              

    Suppose the file input.txt contains the following integers:

    8 8 3 5 1 7 0 9 ii 6 9 7 4 0 5 3 9 iii 7 six              

    What is the contents of the assortment a after running the post-obit command

    coffee Mystery 10 < input.txt              
  38. High-low. Shuffle a deck of cards, and deal ane to the player. Prompt the player to guess whether the adjacent card is higher or lower than the current card. Repeat until player guesses it wrong. Game show: ???? used this.
  39. Rubberband collisions. Write a plan CollidingBalls.java that takes a command-line argument n and plots the trajectories of north billowy balls that bounce of the walls and each other according to the laws of elastic collisions. Presume all the balls take the same mass.
  40. Elastic collisions with obstacles. Each ball should have its ain mass. Put a big brawl in the heart with naught initial velocity. Brownian motion.
  41. Statistical outliers. Change Average.java to impress out all the values that are larger than 1.v standard deviations from the mean. You will need an array to store the values.
  42. Optical illusions. Create a Kofka ring or one of the other optical illusions collected by Edward Adelson.
  43. Computer animation. In 1995 James Gosling presented a demonstration of Coffee to Sunday executives, illustrating its potential to evangelize dynamic and interactive Spider web content. At the time, spider web pages were stock-still and non-interactive. To demonstrate what the Web could be, Gosling presented applets to rotate 3D molecules, visualize sorting routines, and Knuckles cart-wheeling across the screen. Java was officially introduced in May 1995 and widely adopted in the technology sector. The Cyberspace would never be the same.
    Duke doing cartwheels
    Program Duke.coffee reads in the 17 images T1.gif through T17.gif and produces the blitheness. To execute on your computer, download the 17 GIF files and put in the aforementioned directory as Duke.java. (Alternatively, download and unzip the file duke.goose egg or duke.jar to excerpt all 17 GIFs.)
  44. Cart-wheeling Duke. Alter Duke.java then that information technology cartwheels 5 times across the screen, from right to left, wrapping around when it hits the window purlieus. Repeat this cart-wheeling wheel 100 times. Hint: after displaying a sequence of 17 frames, move 57 pixels to the left and repeat. Name your program MoreDuke.java.
  45. Tac (cat backwards). Write a plan Tac.java that reads lines of text from standard input and prints the lines out in reverse order.
  46. Game. Implement the game dodge using StdDraw: move a blue disc inside the unit square to touch a randomly placed green disc, while avoiding the moving cherry discs. Subsequently each touch, add a new moving red disc.
  47. Unproblematic harmonic motion. Create an animation like the one below from Wikipedia of simple harmonic motion.

    Simple harmonic motion

  48. Yin yang. Describe a yin yang using StdDraw.arc().
  49. Xx questions. Write a program QuestionsTwenty.java that plays 20 questions from the opposite point of view: the user thinks of a number betwixt ane and a meg and the computer makes the guesses. Use binary search to ensure that the computer needs at most 20 guesses.
  50. Write a programme 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's, run your program with the following command:
    %                  java DeleteX < input.txt > output.txt                
  51. Write a program ThreeLargest.java that reads integers from standard input and prints out the three largest inputs.
  52. Write a program Pnorm.coffee that takes a command-line argument p, reads in real numbers from standard input, and prints out their p-norm. The p-norm norm of a vector (x1, ..., 10N) is divers to be the pth root of (|101|p + |x2|p + ... + |xDue north|p).
  53. Consider the following Java program.
    public form Mystery {    public static void main(String[] args) {       int i = StdIn.readInt();       int j = StdIn.readInt();       System.out.println((i-1));       System.out.println((j*i));    } }                

    Suppose that the file input.txt contains

    What does the following command practice?
  54. Repeat the previous exercise but employ the post-obit command instead
    coffee Mystery < input.txt | coffee Mystery | java Mystery | java Mystery                
  55. Consider the post-obit Coffee plan.
    public class Mystery {    public static void main(String[] args) {       int i = StdIn.readInt();       int j = StdIn.readInt();       int chiliad = i + j;       System.out.println(j);       System.out.println(k);    } }                

    Suppose that the file input.txt contains the integers ane and i. What does the following command practise?

    java Mystery < input.txt | java Mystery | java Mystery | java Mystery                
  56. Consider the Java plan Ruler.java.
    public form Ruler {     public static void main(Cord[] args) {        int n = StdIn.readInt();       String south = StdIn.readString();       Arrangement.out.println((n+1) + " " + s + (n+1)  + s);    } }                

    Suppose that the file input.txt contains the integers 1 and 1. What does the following command do?

    java Ruler < input.txt | java Ruler | coffee Ruler | java Ruler                
  57. Modify Add together.coffee so that information technology re-asks the user to enter two positive integers if the user types in a non-positive integer.
  58. Alter TwentyQuestions.coffee then that information technology re-asks the user to enter a response if the user types in something other than true or faux. Hint: add a do-while loop within the main loop.
  59. Nonagram. Write a program to plot a nonagram.
  60. Star polygons. Write a program StarPolygon.java that takes ii command line inputs p and q, and plots the {p/q}-star polygon.
  61. Consummate graph. Write a program to plot that takes an integer N, plots an Due north-gon, where each vertex lies on a circle of radius 256. Then depict a grey line connecting each pair of vertices.
  62. Necker cube. Write a plan NeckerCube.java to plot a Necker cube.
  63. What happens if you lot motion the StdDraw.articulate(Color.BLACK) control to before the outset of the while loop in BouncingBall.java? Respond: try it and discover a nice woven 3d pattern with the given starting velocity and position.
  64. What happens if you change the parameter of StdDraw.testify() to 0 or 1000 in BouncingBall.coffee?
  65. Write a program to plot a circular ring of width 10 similar the 1 below using two calls to StdDraw.filledCircle().
  66. Write a program to plot a round ring of width 10 like the one below using a nested for loop and many calls to StdDraw.signal().
  67. Write a program to plot the Olympic rings.
    Olympic rings http://www.janecky.com/olympics/rings.html
  68. Write a program BouncingBallDeluxe.java that embellishes BouncingBall.java past playing a sound consequence upon collision with the wall using StdAudio and the sound file pipebang.wav.

stclairreaked.blogspot.com

Source: https://introcs.cs.princeton.edu/15inout

0 Response to "How to Read Commands From Keyboard Java for Game"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel