Input and output.

Typically, we want to provide input to our programs: data that they can process to produce a result. The simplest way to provide input data is illustrated in UseArgument.java. Whenever this program is executed, it reads the command-line argument that you type after the program name and prints it back out to the terminal as part of the message.
% javac UseArgument.java
% java UseArgument Alice
Hi, Alice. How are you?
% java UseArgument Bob
Hi, Bob. How are you?

Exercises

  1. Describe what happens if, in HelloWorld.java, you omit
    1. public
    2. static
    3. void
    4. args
  2. Describe what happens if, in HelloWorld.java, you omit
    1. main
    2. String
    3. HelloWorld
    4. System.out
    5. println
  3. Describe what happens if, in HelloWorld.java, you omit
    1. the ;
    2. the first "
    3. the second "
    4. the first {
    5. the second {
    6. the first }
    7. the second }
  4. Describe what happens if, in HelloWorld.java, you misspell (by, say, omitting the second letter)
    1. main
    2. String
    3. HelloWorld
    4. System.out
    5. println
  5. Describe what happens if you try to execute Hi.java with:
    1. java Hi
    2. java Hi @!&^%
    3. java Hi 1234
    4. java Hi.class Bob
    5. java Hi.java Bob
    6. java Hi Alice Bob
  6. Modify UseArgument.java to make a program UseThree.java that takes three names and prints out a proper sentence with the names in the reverse of the order given, so that for example, "java UseThree Alice Bob Carol" gives "Hi Carol, Bob, and Alice.".
  7. Write a program Initials.java that prints your initials using nine rows of asterisks like the one below.
    **        ***    **********      **             *             **
    **      ***      **        **     **           ***           **
    **    ***        **         **     **         ** **         **
    **  ***          **          **     **       **   **       **
    *****            **          **      **     **     **     **
    **  ***          **          **       **   **       **   **
    **    ***        **         **         ** **         ** **
    **      ***      **        **           ***           ***
    **        ***    **********              *             *
      
  8. I typed in the following program. It compiles fine, but when I execute it, I get the error java.lang.NoSuchMethodError: main. What am I doing wrong?
    public class Hello {
       public static void main() {
          System.out.println("Doesn't execute");   
       }
    }
    
  9. Write a program that uses Math.sin() and Math.cos() to check that the value of sin2θ + cos2θ is approximately 1 for any θ entered as a command-line argument. Just print the value. Why are the values not always exactly 1?
  10. Suppose that a and b are boolean values. Show that the expression (!(a && b) && (a || b)) || ((a && b) || !(a || b)) is equivalent to true.
  11. Suppose that a and b are int values. Simplify the following expression: (!(a < b) && !(a > b))
  12. Why does 10/3 give 3 and not 3.33333333?
  13. What do each of the following print?
    1. System.out.println(2 + "bc");
    2. System.out.println(2 + 3 + "bc");
    3. System.out.println((2+3) + "bc");
    4. System.out.println("bc" + (2+3));
    5. System.out.println("bc" + 2 + 3);
    Explain each outcome.
  14. Explain how to use Quadratic.java to find the square root of a number.
  15. What do each of the following print?
    1. System.out.println('b');
    2. System.out.println('b' + 'c');
    3. System.out.println((char) ('a' + 4));
    Explain each outcome.
  16. Suppose that a variable a is declared as int a = 2147483647 (or equivalently, Integer.MAX_VALUE). What do each of the following print?
    1. System.out.println(a);
    2. System.out.println(a + 1);
    3. System.out.println(2 - a);
    4. System.out.println(-2 - a);
    5. System.out.println(2 * a);
    6. System.out.println(4 * a);
    Explain each outcome.
  17. Suppose that a variable a is declared as double a = 3.14159. What do each of the following print?
    1. System.out.println(a);
    2. System.out.println(a + 1);
    3. System.out.println(8 / (int) a);
    4. System.out.println(8 / a);
    5. System.out.println(8 / a);
    6. System.out.println((int) (8 / a);
    Explain each outcome.
  18. What is the value of (Math.sqrt(2) * Math.sqrt(2) == 2)?
  19. Write a program that takes two positive integers as command-line arguments and prints true if either evenly divides the other.
  20. Write a program that takes three positive integers as command-line arguments and prints true if any one of them is greater than or equal to the sum of the other two and false otherwise. (Note : This computation tests whether the three numbers could be the lengths of the sides of some triangle.)
  21. A physics student gets unexpected results when using the code
    F = G * mass1 * mass2 / r * r;
    to compute values according to the formula F = G m1 m2 / r^2. Explain the problem and correct the code.
  22. Give the value of a after the execution of each of the following sequences:
    int a = 1;             boolean a = true;      int a = 2;  
    a = a + a;             a = !a;                a = a * a; 
    a = a + a;             a = !a;                a = a * a; 
    a = a + a;             a = !a;                a = a * a; 
      
  23. Suppose that x and y are double values that represent the Cartesian coordinates of a point (x, y) in the plane. Give an expression whose value is the distance of the point from the origin.
  24. Write a program that takes two int values a and b from the command line and prints a random integer between a and b.
  25. Write a program SumOfTwoDice.java that prints the sum of two random integers between 1 and 6 (such as you might get when rolling dice).
  26. Write a program that takes a double value t from the command line and prints the value of sin(2t) + sin(3t).
  27. Write a program that takes three double values x0, v0, and t from the command line and prints the value of x0 + v0*t + 1/2 gt^2, where g is the constant 9.800722 m/s^2. (Note : This value the displacement in meters after t seconds when an object is thrown straight up from initial position x0 at velocity v0 meters per second.)
  28. Write a program SpringSeason.java that takes two int values m and d from the command line and prints true if day d of month m is between March 20 (m = 3, d =20) and June 20 (m = 6, d = 20), false otherwise.
  29. Loan payments. Write a program that calculates the monthly payments you would have to make over a given number of years to pay off a loan at a given interest rate compounded continuously, taking the number of years t, the principal P, and the annual interest rate r as command-line arguments. The desired value is given by the formula Pe^(rt). Use Math.exp().
  30. Wind chill. Given the temperature t (in Fahrenheit) and the wind speed v (in miles per hour), the National Weather Service defines the effective temperature (the wind chill) to be:
    w = 35.74 + 0.6215 t + (0.4275 t - 35.75) v0.16
    Write a program WindChill.java that takes two double command-line arguments t and v and prints out the wind chill. Use Math.pow(a, b) to compute ab. Note: the formula is not valid if t is larger than 50 in absolute value or if v is larger than 120 or less than 3 (you may assume that the values you get are in that range).
  31. Polar coordinates. Write a program CartesianToPolar.java that converts from Cartesian to polar coordinates. Your program should take two real numbers x and y on the command line and print the polar coordinates r and θ. Use the Java method Math.atan2(y, x), which computes the arctangent value of y/x that is in the range from -π to π.
  32. Gaussian random numbers. One way to generate a random number taken from the Gaussian distribution is to use the Box-Muller formula
    Z = sin(2 π v) (-2 ln u)1/2
    where u and v and real numbers between 0 and 1 generated by the Math.random() method. Write a program StdGaussian.java that prints out a standard Gaussian random variable.
  33. Order check. Write a program that takes three double values x, y, and z as command-line arguments and prints true if the values are strictly ascending or descending (x < y < z or x > y > z), and false otherwise.
  34. Day of the week. Write a program DayOfWeek.java that takes a date as input and prints the day of the week that date falls on. Your program should take three command-line arguments: m (month), d (day), and y (year). For m use 1 for January, 2 for February, and so forth. For output print 0 for Sunday, 1 for Monday, 2 for Tuesday, and so forth. Use the following formulas, for the Gregorian calendar:
    y0 = y - (14 - m) / 12
    x = y0 + y0/4 - y0/100 + y0/400
    m0 = m + 12 * ((14 - m) / 12) - 2
    d0 = (d + x + (31*m0)/ 12) mod 7
    
    For example, on what day of the week was August 2, 1953?
    y = 1953 - 0 = 1953
    x = 1953 + 1953/4 - 1953/100 + 1953/400 = 2426
    m = 8 + 12*0 - 2 = 6
    d = (2 + 2426 + (31*6) / 12) mod 7 = 2443 mod 7 = 0  (Sunday)
    
  35. Uniform random numbers. Write a program Stats5.java that prints five uniform random values between 0 and 1, their average value, and their minimum and maximum value. Use Math.random(), Math.min(), and Math.max().
  36. Mercator projection. The Mercator projection is a conformal (angle preserving) projection that maps latitude φ and longitude λ to rectangular coordinates (x, y). It is widely used - for example, in nautical charts and in the maps that you print from the web. The project is defined by the equations
    x = λ - λ0
    y = 1/2 ln((1 + sin φ) / (1 - sin φ))
    
    where &lambda0 is the longitude of the point in the center of the map. Write a program that takes &lambda0 and the latitude and longitude of a point from the command line and prints its projection.
  37. Color conversion. Several different formats are used to represent color. For example, the primary format for LCD displays, digital cameras, and web pages, known as the RGB format, specifies the level of red (R), green (G), and blue (B) on an integer scale from 0 to 255. The primary format for publishing books and magazines, known as the CMYK format, specifies the level of cyan (C), magenta (M), yellow (Y), and black (K) on a real scale from 0.0 to 1.0. Write a program RG- BtoCMYK that converts RGB to CMYK. Take three integers - red, green, and blue - from the command line and print the equivalent CMYK values. If the RGB values are all 0, then the CMY values are all 0 and the K value is 1; otherwise, use these formulas:
    RGB to CMYK formula
    % java RGBtoCMYK 75 0 130       // indigo
    cyan    = 0.4230769230769229
    magenta = 1.0
    yellow  = 0.0
    black   = 0.4901960784313726
    
  38. Great circle. Write a program GreatCircle.java that takes four command-line arguments - x1, y1, x2, and y2 - (the latitude and longitude, in degrees, of two points on the earth) and prints out the great-circle distance between them. The great-circle distance d (in nautical miles) is given by the formula derived from the law of cosines:
    Great circle distance formula
    Note that this equation uses degrees, whereas Java's trigonometric functions use radians. Use Math.toRadians() and Math.toDegrees() to convert between the two. Use your program to compute the great-circle distance between paris 48.87° N, -2.33° W) and San Francisco (37.8° N, 122.4° W).

    Note: the shape of the earth is more like a flattened spheroid than a sphere, so the formula above is only an approximation (up to around 0.5% error). Also, this formula is unreliable for small distances because the inverse cosine function is ill-conditioned.

    Here is the Haversine formula:

    a = sin^2(L2-L1)/2) + cos(L1) * cos(L2) * sin^2((G2-G1)/2)
    c = 2 * arcsin(min(1, sqrt(a)))  // distance in radians
    distance = 60 * c                // nautical miles
    

    The Haversine formula is accurate for most distances, but it suffers from rounding errors when the points are (nearly) antipodal. The following formula is accurate for all distances.

    double delta = G1 - G2;  
    double p1 = cos(L2) * sin(delta);
    double p2 = cos(L1) * sin(L2) - sin(L1) * cos(L2) * cos(delta);  
    double p3 = sin(L1) * sin(L2) + cos(L1) * cos(L2) * cos(delta);
    distance = 60 * Math.atan2(Math.sqrt(p1*p1 + p2*p2), p3);
    

    Kahan reference.

  39. Three-sort. Write a program ThreeSort.java that takes three int values from the command line and prints them in ascending order. Use Math.min() and Math.max().
  40. Write a program Distance.java that takes two integer command-line arguments x and y and outputs the Euclidan distance from the point (x, y) to the origin (0, 0).
  41. Write a program Swap.java that takes two integer command-line arguments a and b and swaps their values. After each assignment statement, use System.out.println() to print out a trace of the variables.
  42. What does the following statement do where grade is a variable of type int?
    boolean isA = (90 <= grade <= 100);
        

    Solution. Syntax error since <= is a binary operator. You can rewrite the expression as (90 <= grade && grade <= 100).

  43. RGB to YIQ color converter. Write a program RGBtoYIQ.javathat takes an RGB color (three integers between 0 and 255) and transforms it to an YIQ color (three different integers between 0 and 255). Write a program YIQtoRGB.java that applies the inverse transformation.
  44. CMYK to RGB color matching. Write a program CMYKtoRGB that reads in four command line inputs C, M, Y, and K between 0 and 1, and prints out the corresponding RGB parameters. Devise the appropriate formula by "inverting" the RGB to CMYK conversion formula.
  45. What does the following code fragment print out?
    double x = (double) (3/5);
    System.out.println(x);
      
  46. Why doesn't the following program print out 4294967296 = 2^32?
    int x = 65536;
    long y = x * x;
    System.out.println(y);
      
  47. What is the value of (Math.sqrt(2) * Math.sqrt(2) == 2)?
  48. Guess the biggest number. Consider the following game. Alice writes down two integers between 0 and 100 on two cards. Bob gets to select one of the two cards and see its value. After looking at the value, Bob commits to one of the two cards. If he chooses a card with the largest value, he wins; otherwise he loses. Devise a strategy (and corresponding computer program) for Bob so that he guarantees to win strictly more than half the time.
  49. Fibonacci word. Write a program FibonacciWord.java that prints the Fibonacci word of order 0 through 10. f(0) = "a", f(1) = "b", f(2) = "ba", f(3) = "bab", f(4) = "babba", and in general f(n) = f(n-1) followed by f(n-2). Use string concatenation.
  50. Standard deviation. Modify Exercise 35 so that it prints out the sample standard deviation in addition to the average.
  51. Write a program that reads in three parameters and prints true if all three are equal, and false otherwise.
  52. What happens if you compile LeapYear.java and execute it with
    1. java LeapYear
    2. java LeapYear 1975.5
    3. java LeapYear -1975
    4. java LeapYear 1975 1976 1977
  53. What does the compiler do if you try to write the following expression:
    int a = 27 * "three";
      
  54. What does the compiler do if you try to write the following expression:
    double x;
    System.out.println(x);
      
  55. What does the following code fragment print.
    int threeInt = 3;
    int fourInt  = 4;
    double threeDouble = 3.0;
    double fourDouble  = 4.0;
    System.out.println(threeInt / fourInt);
    System.out.println(threeInt / fourDouble);
    System.out.println(threeDouble / fourInt);
    System.out.println(threeDouble / fourDouble);
      
  56. Write a program that takes four real-valued command line parameters x1, y1, x2, and y2 and prints the Euclidean distance between the points (x1, y1) and (x2, y2). Use Math.sqrt().
  57. Write a program Ordered.java that reads in three integer command line arguments, x, y, and z. Create a boolean variable b that is true if the three values are either in ascending or in descending order, and false otherwise. Print out the variable b.
  58. Write a program Divisibility.java that reads in two command line inputs and prints true if both are divisible by 7, and false otherwise.
  59. Area of a triangle. Write a program TriangleArea.java that takes three command line inputs a, b, and c, representing the side lengths of a triangle, and prints out the area of the triangle using Heron's formula: area = sqrt(s(s-a)(s-b)(s-c)), where s = (a + b + c) / 2.
  60. Equatorial to horizontal coordinates. The equatorial coordinate system is widely used by astronomers to indicate the position of a star on the celestial sphere. The position is specified by its declination δ, its hour angle H, and its latitude φ. The horizontal coordinate system (a.k.a. Alt/Az coordinate system) is useful for determining the setting/rising time of celestial objects. The position is specified by its altitude (vertical angle from the horizon) and and its azimuth (horizontal angle). Given a star's position using equatorial coordinates, find its position in horizontal coordinates using the formulas below.
    Altitude = asin (sin φ sin δ  + cos φ cos δ cos H)
    Azimuth  = acos ((cos φ sin δ  - sin φ cos δ cos H) / cos (Altitude) )
        
  61. Body mass index. The body mass index (BMI) is the ratio of the weight of a person (in kilograms) to the square of the height (in meters). Write a program BMI.java that takes two command-line arguments, weight and height, and prints out the BMI.
  62. Temperature conversion. What is wrong with the following code fragment to convert from Fahrenheit (F) to Celsius (C)?
    double C = (F - 32) * (5 / 9);
      
  63. Exponentiation. What is wrong with the following code fragment to compute a2, where a is of type double?
    double b = a^2;
        
  64. What of the following statements is legal?
    boolean b = 1;
    boolean b = true;
    boolean b = "true";
    boolean b = True;
      
  65. Barring overflow, give a code fragment to compute the maximum of two integers a and b without using Math.max() or if.
    int max = (a + b + Math.abs(a - b)) / 2;
        
  66. Discriminant of cubic polynomial. Given the coefficients b, c, and d of the cubic polynomial x^3 + bx^2 + cx + d, the discriminant is b^2c^2 - 4c^3 - 4b^3d - 27d^2 + 18bcd.
  67. Barycenter. In a two-body system, the barycenter is the center of gravity about which the two celestial bodies orbit each other. Given the masses m1 and m2 of the two bodies, and the shortest distance a between the two bodies, the distance from the center of the first (more massive) body to the barycenter is r1 = a m2 / (m1 + m2). Give the radius R1 of the first body, compute the ratio r1 / R1. If it is less than 1, the barycenter lies within the first body. Masses are in earth-mass units, distances are in kilometers.

    Earth-moon: m1 = 1, m2 = .0123, a = 384,000, r1 = 4,670, R1 = 6,380.

    Pluto-Charon: m1 = .0021, m2 = .000254, a = 19,600, r1 = 2,110, R1 = 1,150.

    Sun-Earth: m1 = 333,000, m2 = 1, a = 150,000,000, r1 = 449, R1 = 696,000.