Determine if the Line Read From the File Is a Double or an Integer
i.iii Conditionals and Loops
In the programs that we accept examined to this point, each of the statements is executed once, in the order given. About programs are more complicated because the sequence of statements and the number of times each is executed can vary. We use the term control flow to refer to argument sequencing in a plan.
If statements.
Most computations require different actions for different inputs.
- The following code fragment uses an if argument to put the smaller of two int values in ten and the larger of the two values in y, by exchanging the values in the two variables if necessary.
- Flip.java uses Math.random() and an if-else statement to print the results of a coin flip.
- The table below summarizes some typical situations where y'all might need to use an if or if-else statement.
While loops.
Many computations are inherently repetitive. The
whileloop enables usa to execute a group of statements many times. This enables usa to express lengthy computations without writing lots of lawmaking.
- The post-obit lawmaking fragment computes the largest power of ii that is less than or equal to a given positive integer n.
- TenHellos.coffee prints "Howdy World" 10 times.
- PowersOfTwo.java takes an integer control-line argument n and prints all of the powers of 2 less than or equal to north.
For loops.
The for loop is an alternate Java construct that allows us even more flexibility when writing loops.
- For note. Many loops follow the same basic scheme: initialize an index variable to some value and and then use a while loop to exam an leave status involving the index variable, using the last statement in the while loop to modify the index variable. Java'due south for loop is a straight way to express such loops.
- Chemical compound assignment idioms. The idiom i++ is a shorthand annotation for i = i + 1.
- Scope. The scope of a variable is the part of the program that can refer to that variable by name. Generally the telescopic of a variable comprises the statements that follow the declaration in the aforementioned block as the announcement. For this purpose, the code in the for loop header is considered to be in the same cake as the for loop trunk.
Nesting.
The
if,
while, and
forstatements have the aforementioned condition as consignment statements or whatever other statements in Java; that is, we can use them wherever a statement is called for. In particular, we tin can apply one or more of them in the torso of another statement to make compound statements. To emphasize the nesting, nosotros utilise indentation in the programme lawmaking.
- DivisorPattern.coffee has a for loop whose body contains a for loop (whose torso is an if-else argument) and a impress statement. It prints a pattern of asterisks where the ithursday row has an asterisk in each position corresponding to divisors of i (the same holds true for the columns).
- MarginalTaxRate.coffee computes the marginal tax rate for a given income. It uses several nested if-else statements to test from among a number of mutually sectional possibilities.
Loop examples.
Applications.
The ability to programme with loops and conditionals immediately opens up the world of computation to usa.
- Ruler subdivisions. RulerN.java takes an integer command-line argument due north and prints the string of ruler subdivision lengths. This program illustrates one of the essential characteristics of loops—the program could hardly be simpler, but information technology can produce a huge corporeality of output.
- Finite sums. The computational paradigm used in PowersOfTwo.java is ane that y'all will use ofttimes. It uses two variables—one every bit an index that controls a loop, and the other to accrue a computational result. Programme HarmonicNumber.coffee uses the aforementioned image to evaluate the sum
$$ H_n = \frac{1}{i} + \frac{1}{2} + \frac{1}{iii} + \frac{1}{four} + \; \ldots \; + \frac{ane}{n} $$
These numbers, which are known as the harmonic numbers, arise frequently in the analysis of algorithms.
- Newton'due south method.
Sqrt.java uses a archetype iterative technique known as Newton's method to compute the square root of a positive number x: First with an judge t. If t is equal to ten/t (upwards to machine precision), and then t is equal to a square root of x, so the ciphering is complete. If non, refine the gauge by replacing t with the average of t and 10/t. Each time we perform this update, we become closer to the desired answer. - Number conversion. Binary.coffee prints the binary (base ii) representation of the decimal number typed every bit the command-line argument. It is based on decomposing the number into a sum of powers of ii. For instance, the binary representation of 106 is 11010102, which is the same every bit saying that 106 = 64 + 32 + 8 + 2. To compute the binary representation of due north, we consider the powers of 2 less than or equal to n in decreasing guild to determine which belong in the binary decomposition (and therefore represent to a i chip in the binary representation).
- Gambler's ruin.
Suppose a gambler makes a serial of fair $1 bets, starting with $50, and proceed to play until she either goes broke or has $250. What are the chances that she volition become home with $250, and how many bets might she expect to make before winning or losing? Gambler.coffee is a simulation that can help reply these questions. It takes iii command-line arguments, the initial stake ($50), the goal corporeality ($250), and the number of times we want to simulate the game. - Prime factorization. Factors.java takes an integer command-line argument n and prints its prime number factorization. In dissimilarity to many of the other programs that we take seen (which nosotros could exercise in a few minutes with a calculator or pencil and newspaper), this ciphering would not be viable without a computer.
Other conditional and loop constructs.
To be complete, we consider 4 more than Coffee constructs related to conditionals and loops. They are used much less ofttimes than the
if,
while, and
forstatements that we've been working with, just it is worthwhile to exist aware of them.
- Break statements. In some situations, we want to immediate exit a loop without letting it run to completion. Java provides the break argument for this purpose. Prime.java takes an integer command-line argument due north and prints true if n is prime, and faux otherwise. There are two different means to go out this loop: either the break statement is executed (because n is not prime) or the loop-continuation condition is not satisfied (because north is prime).
Note that the intermission statement does not apply to if or if-else statements. In a famous programming problems, the U.S. telephone network crashed because a programmer intended to utilize a pause statement to exit a complicated if statement.
- Go on statements. Java besides provides a mode to skip to the adjacent iteration of a loop: the go on statement. When a continue is executed within the body of a for loopy, the flow of command transfers straight to the increment statement for the side by side iteration of the loop.
- Switch statements. The if and if-else statements allow one or ii alternatives. Sometimes, a computation naturally suggests more than than ii mutually exclusive alternatives. Java provides the switch argument for this purpose. NameOfDay.java takes an integer betwixt 0 and vi as a control-line argument and uses a switch statement to print the corresponding name of the day (Sunday to Sat).
- Do–while loops. A do-while loop is almost the same as a while loop except that the loop-continuation condition is omitted the first time through the loop. RandomPointInCircle.java sets x and y so that (10, y) is randomly distributed within the circle centered at (0, 0) with radius 1.
With Math.random() we become points that are randomly distributed in the ii-by-2 foursquare centre at (0, 0). Nosotros but generate points in this region until we find i that lies within the unit disk. We always want to generate at least one point so a do-while loop is most advisable. We must declare x and y outside the loop since we volition want to access their values afterwards the loop terminates.
We don't utilise the post-obit 2 menstruation control statements in this textbook, just include them here for completeness.
- Conditional operator. The provisional operator ?: is a ternary operator (three operands) that enables you to embed a conditional inside an expression. The three operands are separated by the ? and : symbols. If the first operand (a boolean expression) is true, the result has the value of the second expression; otherwise it has the value of the third expression.
int min = (10 < y) ? 10 : y;
- Labeled suspension and keep statements. The intermission and proceed statements use to the innermost for or while loop. Sometimes we want to leap out of several levels of nested loops. Java provides the labeled break and labeled continue statements to accomplish this. Here is an example.
Exercises
- Write a program AllEqual.java that takes three integer control-line arguments and prints equal if all three are equal, and not equal otherwise.
- Write a program RollLoadedDie.java that prints the result of rolling a loaded die such that the probability of getting a 1, 2, iii, 4, or 5 is 1/eight and the probability of getting a 6 is three/8.
- Rewrite TenHellos.java to brand a program Hellos.coffee that takes the number of lines to print as a command-line statement. Yous may assume that the argument is less than 1000. Hint: consider using i % 10 and i % 100 to determine whether to use "st", "nd", "rd", or "thursday" for press the ith Hello.
- Write a programme FivePerLine.java that, using ane for loop and one if statement, prints the integers from 1000 to 2000 with v integers per line. Hint: use the % operator.
- Write a programme FunctionGrowth.java that prints a table of the values of ln due north, n, north ln n, nii , n3 , and 2n for n = 16, 32, 64, ..., 2048. Use tabs ('\t' characters) to line upward columns.
- What is the value of 1000 and due north after executing the post-obit lawmaking?
int n = 123456789; int m = 0; while (n != 0) { thou = (ten * m) + (n % 10); n = n / 10; } - What does the post-obit code print out?
int f = 0, g = 1; for (int i = 0; i <= xv; i++) { Arrangement.out.println(f); f = f + thousand; one thousand = f - thousand; } - Unlike the harmonic numbers, the sum one/1 + 1/four + one/nine + one/16 + ... + 1/northwardii does converge to a constant as northward grows to infinity. (Indeed, the constant is πtwo / half dozen, so this formula tin can exist used to estimate the value of π.) Which of the following for loops computes this sum? Assume that n is an int initialized to million and sum is a double initialized to 0.
(a) for (int i = 1; i <= north; i++) sum = sum + 1 / (i * i); (b) for (int i = 1; i <= n; i++) sum = sum + 1.0 / i * i; (c) for (int i = 1; i <= north; i++) sum = sum + ane.0 / (i * i); (d) for (int i = 1; i <= n; i++) sum = sum + 1 / (one.0 * i * i);
- Alter Binary.java to get a program Alter Kary.java that takes a 2nd command-line argument K and converts the first argument to base K. Assume the base of operations is between 2 and sixteen. For bases greater than 10, use the messages A through F to stand for the 11th through 16th digits, respectively.
- Write a program code fragment that puts the binary representation of a positive integer north into a String variable s.
Artistic Exercises
- Ramanujan's taxi. South. Ramanujan was an Indian mathematician who became famous for his intuition for numbers. When the English language mathematician G. H. Hardy came to visit him in the infirmary i day, Hardy remarked that the number of his taxi was 1729, a rather tedious number. To which Ramanujan replied, "No, Hardy! No, Hardy! It is a very interesting number. It is the smallest number expressible as the sum of two cubes in two dissimilar means." Verify this claim by writing a program Ramanujan.java that takes an integer control-line argument northward and prints all integers less than or equal to due north that can exist expressed as the sum of ii cubes in two different ways - discover distinct positive integers a, b, c, and d such that a3 + b3 = cthree + d3 . Employ 4 nested for loops.
Now, the license plate 87539319 seems like a rather ho-hum number. Determine why it's not.
- Checksums. The International Standard Book Number (ISBN) is a ten digit lawmaking that uniquely specifies a book. The rightmost digit is a checksum digit which tin be uniquely determined from the other nine digits from the condition that d1 + 2d2 + 3dthree + ... + 10dx must be a multiple of 11 (here di denotes the ith digit from the right). The checksum digit d1 can exist any value from 0 to 10: the ISBN convention is to utilize the value X to announce 10. Example: the checksum digit corresponding to 020131452 is 5 since is the just value of done betwixt 0 and and 10 for which d1 + 2*two + three*5 + iv*iv + 5*ane + 6*3 + seven*1 + 8*0 + ix*2 + 10*0 is a multiple of 11. Write a program ISBN.java that takes a 9-digit integer as a command-line argument, computes the checksum, and prints the 10-digit ISBN number. It'due south ok if y'all don't impress any leading 0s.
- Exponential function. Assume that ten is a positive variable of type double. Write a plan Exp.java that computes e^x using the Taylor series expansion
$$ eastward^ ten = one + x + \frac{10^2}{2!} + \frac{x^iii}{3!} + \frac{x^four}{4!} + \ldots $$
- Trigonometric functions. Write ii programs Sin.java and Cos.java that compute sin x and cos x using the Taylor series expansions
$$ \sin x = x - \frac{x^3}{3!} + \frac{x^five}{five!} - \frac{10^seven}{7!} + \ldots $$
$$ \cos x = 1 - \frac{x^two}{two!} + \frac{ten^iv}{4!} - \frac{x^6}{6!} + \ldots $$
- Game simulation. In the game evidence Allow'due south Brand a Deal, a contestant is presented with three doors. Behind one door is a valuable prize, behind the other two are gag gifts. After the contestant chooses a door, the host opens upwardly i of the other two doors (never revealing the prize, of course). The contestant is then given the opportunity to switch to the other unopened door. Should the contestant do so? Intuitively, information technology might seem that the contestant'southward initial pick door and the other unopened door are equally likely to contain the prize, so in that location would exist no incentive to switch. Write a program MonteHall.java to examination this intuition by simulation. Your program should take an integer command-line argument north, play the game north times using each of the two strategies (switch or don't switch) and print the chance of success for each strategy. Or you can play the game hither.
- Euler'southward sum-of-powers conjecture. In 1769 Leonhard Euler formulated a generalized version of Fermat's Last Theorem, conjecturing that at to the lowest degree north nth powers are needed to obtain a sum that is itself an northwardthursday power, for due north > 2. Write a programme Euler.java to disprove Euler'southward conjecture (which stood until 1967), using a quintuply nested loop to find four positive integers whose 5th power sums to the 5th ability of some other positive integer. That is, discover a, b, c, d, and eastward such that a 5 + b five + c v + d v = e 5. Use the long information type.
Web Exercises
- Write a plan RollDie.coffee that generates the result of rolling a fair half dozen-sided die (an integer between ane and six).
- Write a program that takes 3 integer command-line arguments a, b, and c and print the number of distinct values (i, 2, or 3) amid a, b, and c.
- Write a program that takes 5 integer command-line arguments and prints the median (the third largest one).
- (hard) Now, try to compute the median of 5 elements such that when executed, it never makes more than 6 total comparisons.
- How can I create in an infinite loop with a for loop?
Solution: for(;;) is the same equally while(truthful).
- What'due south wrong with the post-obit loop?
The while loop condition uses = instead of == so it is an assignment statement (which makes done always false and the body of the loop volition never be executed). It'south improve to manner to avoid using ==.boolean done = false; while (done = false) { ... }boolean done = false; while (!washed) { ... } - What's wrong with the following loop that is intended to compute the sum of the integers ane through 100?
The variable sum should be divers outside the loop. By defining information technology inside the loop, a new variable sum is initialized to 0 each time through the loop; also it is not even accessible outside the loop.for (int i = 1; i <= Northward; i++) { int sum = 0; sum = sum + i; } System.out.println(sum); - Write a program Hurricane.coffee that that takes the wind speed (in miles per hour) equally an integer command-line argument and prints whether information technology qualifies as a hurricane, and if so, whether it is a Category 1, 2, 3, 4, or 5 hurricane. Below is a table of the wind speeds according to the Saffir-Simpson scale.
Category Wind Speed (mph) one 74 - 95 2 96 - 110 3 111 - 130 4 131 - 155 5 155 and above - What is incorrect with the post-obit lawmaking fragment?
double x = -32.two; boolean isPositive = (x > 0); if (isPositive = true) System.out.println(x + " is positive"); else System.out.println(x + " is not positive");
Solution: It uses the assignment operator = instead of the equality operator ==. A better solution is to write if (isPositive).
- Modify/add i character and so that the following program prints 20 xs. There are 2 unlike solutions.
Solution: Supercede the i < due north status with -i < north. Supplant the i-- with n--. ( In C, there is a 3rd: replace the < with a +.)int i = 0, northward = 20; for (i = 0; i < n; i--) System.out.impress("x"); - What does the post-obit code fragment do?
if (x > 0); System.out.println("positive");Solution: always prints positive regardless of the value of x considering of the extra semicolon after the if argument.
- RGB to HSB converter. Write a program RGBtoHSV.coffee that takes an RGB color (iii integers between 0 and 255) and transforms it to an HSB colour (3 unlike integers between 0 and 255). Write a program HSVtoRGB.java that applies the inverse transformation.
- Boys and girls. A couple outset a family decides to keep having children until they have at to the lowest degree 1 of either sex. Estimate the average number of children they will have via simulation. Also estimate the almost common outcome (record the frequency counts for 2, 3, and iv children, and too for v and higher up). Presume that the probability p of having a male child or daughter is 1/two.
- What does the following program exercise?
Solution: Prints all of the powers of 2 less than or equal to due north.public static void chief(String[] args) { int N = Integer.parseInt(args[0]); int x = 1; while (N >= ane) { System.out.println(ten); x = 2 * ten; N = N / 2; } } - Boys and girls. Repeat the previous question, but assume the couple keeps having children until they have another child which is of the same sex activity as the showtime child. How does your answer change if p is different from one/2?
Surprisingly, the average number of children is ii if p = 0 or 1, and 3 for all other values of p. But the most probable value is 2 for all values of p.
- Given ii positive integers a and b, what result does the following code fragment exit in c
c = 0; while (b > 0) { if (b % 2 == 1) c = c + a; b = b / ii; a = a + a; }Solution: a * b.
- Write a program using a loop and four conditionals to print
12 midnight 1am 2am ... 12 noon 1pm ... 11pm
- What does the following plan print?
public grade Exam { public static void primary(String[] args) { if (10 > v); else; { Organization.out.println("Here"); }; } } - Alice tosses a fair money until she sees two sequent heads. Bob tosses another off-white coin until he sees a head followed by a tail. Write a program to estimate the probability that Alice will make fewer tosses than Bob? Solution: 39/121.
- Rewrite DayOfWeek.coffee from Practise 1.ii.29 so that it prints the day of the week as Sunday, Monday, and then forth instead of an integer between 0 and six. Apply a switch statement.
- Number-to-English language. Write a program to read in a command line integer between -999,999,999 and 999,999,999 and impress the English language equivalent. Hither is an exhaustive list of words that your program should apply: negative, zip, one, two, three, four, 5, 6, seven, eight, nine, ten, 11, twelve, thirteen, fourteen, fifteen, xvi, seventeen, eighteen, nineteen, xx, xxx, forty, fifty, threescore, 70, eighty, xc, hundred, 1000, million . Don't utilize hundred, when you lot tin can utilise chiliad, e.1000., use one thousand five hundred instead of xv hundred. Reference.
- Gymnastics judging. A gymnast's score is determined by a panel of 6 judges who each decide a score betwixt 0.0 and ten.0. The final score is determined past discarding the loftier and low scores, and averaging the remaining 4. Write a program GymnasticsScorer.java that takes 6 real control line inputs representing the 6 scores and prints their average, later throwing out the loftier and low scores.
- Quarterback rating. To compare NFL quarterbacks, the NFL devised a the quarterback rating formula based on the quarterbacks number of completed passes (A), pass attempts (B), passing yards (C), touchdown passes (D), and interception (E) equally follows:
- Completion ratio: W = 250/three * ((A / B) - 0.3).
- Yards per laissez passer: 10 = 25/6 * ((C / B) - 3).
- Touchdown ratio: Y = k/3 * (D / B)
- Interception ratio: Z = 1250/iii * (0.095 - (Eastward / B))
- Decimal expansion of rational numbers. Given two integers p and q, the decimal expansion of p/q has an infinitely repeating wheel. For example, ane/33 = 0.03030303.... We employ the note 0.(03) to denote that 03 repeats indefinitely. As another example, 8639/70000 = 0.1234(142857). Write a program DecimalExpansion.java that reads in two command line integers p and q and prints the decimal expansion of p/q using the above notation. Hint: use Floyd's rule.
- Friday the 13th. What is the maximum number of consecutive days in which no Fri the 13th occurs? Hint: The Gregorian calendar repeats itself every 400 years (146097 days) then you only need to worry nearly a 400 year interval.
Solution: 426 (e.thousand., from 8/xiii/1999 to ten/13/2000).
- January 1. Is January one more likely to autumn on a Saturday or Dominicus? Write a programme to make up one's mind the number of times each occurs in a 400 year interval.
Solution: Sun (58 times) is more likely than Saturday (56 times).
- What practise the following two lawmaking fragments do?
for (int i = 0; i < Due north; i++) for (int j = 0; j < North; j++) if (i != j) System.out.println(i + ", " + j); for (int i = 0; i < North; i++) for (int j = 0; (i != j) && (j < Due north); j++) Organization.out.println(i + ", " + j);
- Make up one's mind what value gets printed out without using a computer. Cull the correct answer from 0, 100, 101, 517, or thou.
int cnt = 0; for (int i = 0; i < 10; i++) for (int j = 0; j < 10; j++) for (int grand = 0; m < ten; m++) if (2*i + j >= 3*g) cnt++; Arrangement.out.println(cnt);
- Rewrite CarLoan.java from Creative Exercise XYZ so that it properly handles an involvement rate of 0% and avoids dividing by 0.
- Write the shortest Java program you can that takes an integer command-line argument n and prints truthful if (1 + 2 + ... + n) 2 is equal to (anethree + 23 + ... + n3).
Solution: Always print truthful.
- Modify Sqrt.java and then that information technology reports an error if the user enters a negative number and works properly if the user enters aught.
- What happens if we initialize t to -x instead of x in plan Sqrt.java?
- Sample standard deviation of uniform distribution. Modify Exercise viii so that it prints the sample standard deviation in addition to the average.
- Sample standard deviation of normal distribution. that takes an integer Northward every bit a command-line argument and uses Web Exercise 1 from Section one.2 to print Due north standard normal random variables, and their boilerplate value, and sample standard difference.
- Loaded dice. [Stephen Rudich] Suppose you have three, iii sided die. A: {2, 6, 7}, B: { 1, 5, ix}, and C: {three, 4, viii}. Two players roll a dice and the ane with the highest value wins. Which dice would you choose? Solution: A beats B with probability 5/9, B beats C with probability 5/9 and C beats A with probability 5/9. Be sure to cull second!
- Thue–Morse sequence. Write a program ThueMorse.java that reads in a command line integer n and prints the Thue–Morse sequence of order north. The starting time few strings are 0, 01, 0110, 01101001. Each successive cord is obtained past flipping all of the bits of the previous string and concatenating the result to the finish of the previous string. The sequence has many amazing backdrop. For example, it is a binary sequence that is cube-free: information technology does not contain 000, 111, 010101, or sss where due south is whatsoever string. It is self-similar: if you delete every other bit, you get some other Thue–Morse sequence. It arises in diverse areas of mathematics as well as chess, graphic design, weaving patterns, and music limerick.
- Program Binary.java prints the binary representation of a decimal number n past casting out powers of two. Write an alternate version Program Binary2.java that is based on the following method: Write 1 if n is odd, 0 if n is fifty-fifty. Divide n by ii, throwing away the remainder. Repeat until north = 0 and read the reply backwards. Use % to decide whether n is even, and use string concatenation to course the answer in reverse order.
- What does the following code fragment do?
int digits = 0; do { digits++; n = n / ten; } while (due north > 0);Solution: The number of bits in the binary representation of a natural number n. Nosotros use a do-while loop and so that code output one if n = 0.
- Write a program NPerLine.java that takes an integer control-line argument n and prints the integers from x to 99 with n integers per line.
- Modify NPerLine.java so that it prints the integers from ane to 1000 with due north integers per line. Make the integers line upward by press the right number of spaces before an integer (e.g., three for one-nine, two for 10-99, and one for 100-999).
- Suppose a, b, and c are random number uniformly distributed between 0 and one. What is the probability that a, b, and c form the side length of some triangle? Hint: they volition class a triangle if and simply if the sum of every two values is larger than the tertiary.
- Repeat the previous question, only calculate the probability that the resulting triangle is obtuse, given that the three numbers for a triangle. Hint: the three lengths will form an obtuse triangle if and only if (i) the sum of every two values is larger than the third and (2) the sum of the squares of every ii side lengths is greater than or equal to the foursquare of the third.
Answer.
- What is the value of southward after executing the post-obit code?
int M = 987654321; String s = ""; while (Grand != 0) { int digit = M % 10; s = s + digit; M = M / 10; } - What is the value of i after the following disruptive code is executed?
int i = x; i = i++; i = ++i; i = i++ + ++i;
Moral: don't write code like this.
- Formatted ISBN number. Write a program ISBN2.java that reads in a 9 digit integer from a command-line argument, computes the check digit, and prints the fully formatted ISBN number, e.m, 0-201-31452-5.
- UPC codes. The Universal Production Code (UPC) is a 12 digit code that uniquely specifies a production. The least significant digit di(rightmost one) is a check digit which is the uniquely determined past making the following expression a multiple of 10:
(d1 + dthree + d5 + d7 + d9 + d11) + 3 (d2 + dfour + dhalf dozen + d8 + d10 + d12)
As an example, the check digit corresponding to 0-48500-00102 (Tropicana Pure Premium Orange Juice) is 8 since
(8 + 0 + 0 + 0 + v + 4) + three (ii + ane + 0 + 0 + 8 + 0) = 50
and fifty is a multiple of 10. Write a program that reads in a 11 digit integer from a control line parameter, computes the bank check digit, and prints the the full UPC. Hint: utilize a variable of type long to shop the xi digit number.
- Write a plan that reads in the air current speed (in knots) as a command line statement and prints its force according to the Beaufort scale. Use a switch statement.
- Making change. Write a program that reads in a command line integer N (number of pennies) and prints the all-time way (fewest number of coins) to make change using United states coins (quarters, dimes, nickels, and pennies only). For example, if Due north = 73 so print
2 quarters 2 dimes 3 pennies
Hint: use the greedy algorithm. That is, dispense every bit many quarters as possible, then dimes, and then nickels, and finally pennies.
- Write a program Triangle.java that takes a command-line statement North and prints an North-by-Due north triangular design like the one below.
* * * * * * . * * * * * . . * * * * . . . * * * . . . . * * . . . . . *
- Write a plan Ex.coffee that takes a control-line argument North and prints a (2N + 1)-by-(2N + ane) ex like the one below. Use two for loops and 1 if-else statement.
* . . . . . * . * . . . * . . . * . * . . . . . * . . . . . * . * . . . * . . . * . * . . . . . *
- Write a programme BowTie.coffee that takes a command-line argument N and prints a (2N + 1)-by-(2N + 1) bowtie like the one beneath. Apply two for loops and one if-else argument.
* . . . . . * * * . . . * * * * * . * * * * * * * * * * * * * . * * * * * . . . * * * . . . . . *
- Write a program Diamond.java that takes a control-line argument N and prints a (2N + 1)-by-(2N + one) diamond like the one below.
% java Diamond 4 . . . . * . . . . . . . * * * . . . . . * * * * * . . . * * * * * * * . * * * * * * * * * . * * * * * * * . . . * * * * * . . . . . * * * . . . . . . . * . . . .
- Write a program Heart.java that takes a command-line argument N and prints a centre.
- What does the program Circle.coffee print out when N = 5?
for (int i = -North; i <= Due north; i++) { for (int j = -North; j <= N; j++) { if (i*i + j*j <= N*Due north) System.out.impress("* "); else System.out.print(". "); } System.out.println(); } - Seasons. Write a program Season.java that takes two command line integers M and D and prints the flavour corresponding to month M (one = January, 12 = Dec) and mean solar day D in the northern hemisphere. Utilize the following table
SEASON FROM TO Spring March 21 June 20 Summer June 21 September 22 Fall September 23 December 21 Wintertime December 21 March twenty - Zodiac signs. Write a program Zodiac.java that takes two command line integers One thousand and D and prints the Zodiac sign corresponding to month K (1 = Jan, 12 = Dec) and day D. Use the following table
SIGN FROM TO Capricorn December 22 January xix Aquarius Jan 20 February 17 Pisces Feb xviii March 19 Aries March 20 April nineteen Taurus Apr 20 May twenty Gemini May 21 June xx Cancer June 21 July 22 Leo July 23 August 22 Virgo August 23 September 22 Libra September 23 Oct 22 Scorpio October 23 Nov 21 Sagittarius November 22 December 21 - Muay Thai kickboxing. Write a program that reads in the weight of a Muay Thai kickboxer (in pounds) as a command-line argument and prints their weight class. Apply a switch argument.
Class FROM TO Flyweight 0 112 Super flyweight 112 115 Bantamweight 115 118 Super bantamweight 118 122 Featherweight 122 126 Super featherweight 126 130 Lightweight 130 135 Super lightweight 135 140 Welterweight 140 147 Super welterweight 147 154 Middleweight 154 160 Super middleweight 160 167 Calorie-free heavyweight 167 175 Super light heavyweight 175 183 Cruiserweight 183 190 Heavyweight 190 220 Super heavyweight 220 - - Euler's sum of powers conjecture. In 1769 Euler generalized Fermat's Last Theorem and conjectured that it is incommunicable to notice 3 4th powers whose sum is a quaternary ability, or four fifth powers whose sum is a 5th power, etc. The conjecture was disproved in 1966 by exhaustive computer search. Disprove the conjecture by finding positive integers a, b, c, d, and east such that a5 + b5 + c5 + dv= e5. Write a programme Euler.java that reads in a command line parameter N and exhaustively searches for all such solutions with a, b, c, d, and e less than or equal to N. No counterexamples are known for powers greater than 5, merely y'all can join EulerNet, a distributed calculating effort to find a counterexample for sixth powers.
- Blackjack. Write a program Blackjack.java that takes three command line integers x, y, and z representing your two blackjack cards ten and y, and the dealers face-up card z, and prints the "standard strategy" for a 6 carte du jour deck in Atlantic urban center. Assume that x, y, and z are integers between 1 and x, representing an ace through a confront menu. Written report whether the histrion should hit, stand, or split according to these strategy tables. (When you learn nearly arrays, you will run across an alternate strategy that does non involve as many if-else statements).
- Blackjack with doubling. Modify the previous do to allow doubling.
- Projectile motion. The following equation gives the trajectory of a ballistic missile as a function of the initial angle theta and windspeed: xxxx. Write a java program to print the (ten, y) position of the missile at each time step t. Use trial and error to determine at what angle yous should aim the missile if you hope to incinerate a target located 100 miles due east of your current location and at the same pinnacle. Assume the windspeed is 20 mph due east.
- Earth serial. The baseball game world series is a best of seven contest, where the first team to win 4 games wins the World Series. Suppose the stronger squad has probability p > 1/2 of winning each game. Write a program to judge the chance that the weaker teams wins the Earth Series and to approximate how many games on average information technology will take.
- Consider the equation (9/4)^x = ten^(9/iv). 1 solution is 9/four. Can you find some other ane using Newton'southward method?
- Sorting networks. Write a program Sort3.java with three if statements (and no loops) that reads in three integers a, b, and c from the command line and prints them out in ascending club.
if (a > b) swap a and b if (a > c) bandy a and c if (b > c) swap b and c
- Oblivious sorting network. Convince yourself that the following code fragment rearranges the integers stored in the variables A, B, C, and D and then that A <= B <= C <= D.
Devise a sequence of statements that would sort 5 integers. How many if statements does your program utilise?if (A > B) { t = A; A = B; B = t; } if (B > C) { t = B; B = C; C = t; } if (A > B) { t = A; A = B; B = t; } if (C > D) { t = C; C = D; D = t; } if (B > C) { t = B; B = C; C = t; } if (A > B) { t = A; A = B; B = t; } if (D > E) { t = D; D = Due east; East = t; } if (C > D) { t = C; C = D; D = t; } if (B > C) { t = B; B = C; C = t; } if (A > B) { t = A; A = B; B = t; } - Optimal oblivious sorting networks. Create a program that sorts 4 integers using only v if statements, and i that sorts five integers using only ix if statements of the type above? Oblivious sorting networks are useful for implementing sorting algorithms in hardware. How tin can you lot check that your program works for all inputs?
Solution: Sort4.java sorts 4 elements using 5 compare-exchanges. Sort5.coffee sorts 5 elements using 9 compare-exchanges.
The 0-1 principle asserts that you can verify the correctness of a (deterministic) sorting algorithm by checking whether it correctly sorts an input that is a sequence of 0s and 1s. Thus, to bank check that Sort5.java works, y'all only need to test it on the 2^five = 32 possible inputs of 0s and 1s.
- Optimal oblivious sorting (challenging). Find an optimal sorting network for six, 7, and viii inputs, using 12, 16, and 19 if statements of the course in the previous trouble, respectively.
Solution: Sort6.java is the solution for sorting 6 elements.
- Optimal non-oblivious sorting. Write a program that sorts v inputs using merely 7 comparisons. Hint: Showtime compare the commencement two numbers, the second ii numbers, and the larger of the two groups, and label them so that a < b < d and c < d. 2d, insert the remaining element e into its proper identify in the concatenation a < b < d by first comparing confronting b, then either a or d depending on the outcome. Third, insert c into the proper place in the chain involving a, b, d, and due east in the same style that you lot inserted e (with the noesis that c < d). This uses 3 (first stride) + 2 (second step) + 2 (third step) = 7 comparisons. This method was outset discovered by H. B. Demuth in 1956.
- Weather balloon. (Etter and Ingber, p. 123) Suppose that h(t) = 0.12t4 + 12tiii - 380t2 + 4100t + 220 represents the superlative of a weather airship at time t (measured in hours) for the first 48 hours afterward its launch. Create a table of the pinnacle at time t for t = 0 to 48. What is its maximum height? Solution: t = 5.
- Will the following code fragment compile? If so, what will information technology practice?
int a = x, b = 18; if (a = b) System.out.println("equal"); else Arrangement.out.println("not equal");Solution: Information technology uses the assignment operator = instead of the equality operator == in the conditional. In Java, the outcome of this statement is an integer, but the compiler expects a boolean. As a result, the program will not compile. In some languages (notably C and C++), this lawmaking fragment will gear up the variable a to eighteen and print equal without an fault.
- Gotcha ane. What does the following code fragment do?
Solution: information technology prints yep. Note that the provisional uses = instead of ==. This means that a is assigned the value true As a issue, the provisional expression evaluates to truthful. Coffee is non allowed to the = vs. == error described in the previous exercise. For this reason, it is much better way to use if (a) or if (!a) when testing booleans.boolean a = false; if (a = truthful) System.out.println("yes"); else Organisation.out.println("no"); - Gotcha 2. What does the following code fragment do?
Solution: E'er prints 13 since there is a spurious semicolon after the if statement. Thus, the consignment statement a = xiii; will be executed even though (ten <= y) Information technology is legal (but uncommon) to have a block that does non belong to a conditional argument, loop, or method.int a = 17, ten = v, y = 12; if (x > y); { a = 13; 10 = 23; } System.out.println(a); - Gotcha 3. What does the following code fragment do?
Solution: Information technology goes into an infinite loop printingfor (int ten = 0; ten < 100; x += 0.5) { System.out.println(10); }0. The compound assignment statementx += 0.5is equivalent toten = (int) (10 + 0.five). - What does the post-obit code fragment do?
It does not compile considering the compile cannot guarantee that rate is initialized. Use if-else instead.int income = Integer.parseInt(args[0]); if (income >= 311950) rate = .35; if (income >= 174700) charge per unit = .33; if (income >= 114650) rate = .28; if (income >= 47450) rate = .25; if (income >= 0) rate = .22; System.out.println(charge per unit);
- Application of Newton's method. Write a programme BohrRadius.coffee that finds the radii where the probability of finding the electron in the 4s excited country of hydrogen is cypher. The probability is given by: (ane - 3r/four + r2/eight - r3/192)2 e-r/2 , where r is the radius in units of the Bohr radius (0.529173E-8 cm). Use Newton's method. By starting Newton'due south method at unlike values of r, yous can discover all three roots. Hint: utilize initial values of r= 0, five, and xiii. Challenge: explain what happens if yous use an initial value of r = iv or 12.
- Pepys problem. In 1693, Samuel Pepys asked Isaac Newton which was more than likely: getting at least one 1 when rolling a fair dice 6 times or getting at least two one's when rolling a fair die 12 times. Write a plan Pepys.java that uses simulation to make up one's mind the correct answer.
- What is the value of the variable s afterwards running the post-obit loop when Northward = i, two, 3, 4, and 5.
Cord s = ""; for (int i = 1; i <= N; i++) { if (i % 2 == 0) s = due south + i + southward; else south = i + s + i; }Solution: Palindrome.java.
- Torso mass index. The body mass alphabetize (BMI) is the ratio of the weight of a person (in kilograms) to the foursquare of the height (in meters). Write a program BMI.java that takes two command-line arguments, weight and height, computes the BMI, and prints the corresponding BMI category:
- Starvation: less than fifteen
- Anorexic: less than 17.five
- Underweight: less than 18.5
- Ideal: greater than or equal to 18.5 but less than 25
- Overweight: greater than or equal to 25 but less than 30
- Obese: greater than or equal to 30 but less than 40
- Morbidly Obese: greater than or equal to xl
- Reynolds number. The Reynolds number is the ratio if inertial forces to viscous forces and is an important quantity in fluid dynamics. Write a programme that takes in 4 command-line arguments, the diameter d, the velocity v, the density rho, and the viscosity mu, and prints the Reynold's number d * v * rho / mu (bold all arguments are in SI units). If the Reynold'south number is less than 2000, print laminar flow, if information technology'south betwixt 2000 and 4000, print transient flow, and if it'southward more than 4000, print turbulent flow.
- Wind chill revisited. The air current arctic formula from Practice 1.two.14 is just valid if the wind speed is above 3MPH and below 110MPH and the temperature is below 50 degrees Fahrenheit and above -fifty degrees. Modify your solution to impress an error bulletin if the user types in a value exterior the allowable range.
- Point on a sphere. Write a program to print the (x, y, z) coordinates of a random point on the surface of a sphere. Employ Marsaglia' method: option a random point (a, b) in the unit circumvolve every bit in the do-while example. Then, ready x = 2a sqrt(1 - a^two - b^two), y = 2b sqrt(1 - a^2 - b^2), z = ane - two(a^2 + b^2).
- Powers of k. Write a program PowersOfK.java that takes an integer 1000 as command-line statement and prints all the positive powers of Chiliad in the Java long information type. Note: the constant Long.MAX_VALUE is the value of the largest integer in long.
- Square root, revisited. Why non utilize the loop-continuation status (Math.abs(t*t - c) > EPSILON) in Sqrt.java instead of Math.abs(t - c/t) > t*EPSILON)?
Solution: Surprisingly, it tin can lead to inaccurate results or worse. For example, if you supply SqrtBug.coffee with the control-line argument 1e-fifty, you get 1e-fifty as the answer (instead of 1e-25); if y'all supply 16664444, you get an infinite loop!
- What happens when yous try to compile the following lawmaking fragment?
double x; if (a >= 0) 10 = iii.14; if (a < 0) 10 = two.71; Organization.out.println(10);
Solution: Information technology complains that the variable x might not have been initialized (even though we can clearly see that x will be initialized by ane of the two if statements). You can avoid this problem here past using if-else.
Source: https://introcs.cs.princeton.edu/13flow
0 Response to "Determine if the Line Read From the File Is a Double or an Integer"
ارسال یک نظر