-
What gets printed by the following Java statements? Try and figure this out by
hand first and then check you answers by running them in DrJava.
int x;
x = 4/2;
StdOut.println(x);
x = 7/2;
StdOut.println(x);
x = 1/2;
StdOut.println(x);
-
Recall how you did division in grade school using remainders.
The remainder of 7 ÷ 2 is 1. Two goes into seven three times with one
left over. The remainder is 31 ÷ 4 is 3.
Assuming that x and y are integer variables,
write a Java code segment that uses Java's basic arithmetic operators
of +, -, *, /
and computes and prints the remainder of x ÷ y.
-
What gets printed by the following Java code segment. Again, do this as a mental exercise
and then check your answers in DrJava.
double pi;
int x;
pi = 3.14159;
x = (int) pi * 2;
StdOut.println(x);
-
What gets printed by the Java code segment below. Check your answer in DrJava.
double x;
double y;
x = 2.4;
y = Math.rint(x);
StdOut.println(y);
y = Math.rint(x*x);
StdOut.println(y);
-
Write a Java code segment that calculates the average of three integers x, y,
and z.
-
Write a Java code segment that calculates the average of three integers x, y,
and z
and prints the average rounded to one decimal place. For example the average of 7, 8, and 10
is 3.3. The average of 7, 8, and 11 is 8.7.
-
What does DrJava tell you when you forget to declare a variable?
-
The number 2147483647 is special in Computer Science (believe it or not).
Assign this value to an integer variable and then add one to it like in the code below:
int x;
x = 2147483647;
StdOut.println(x + 1);
-
What happens when you execute it? What can you conclude about
this special number?
- What happens if you change the assignment statement to read
x = 2147483648;
-
Read the short Wikipedia entry about this number.
What does it have to do with computing?
-
Not an exercise: but here's something related.
-
Examine the following code. Mathematically
x and
y should be equal. What value should they be equal to?
What happens when you execute the code? Can you explain what is going on?
double x,y;
x = 1 - (1/3.0 + 1/3.0 + 1/3.0);
y = 1 - 1/3.0 - 1/3.0 - 1/3.0;
StdOut.println(x);
StdOut.println(y);
-
In Physics Newton's law of gravitation says that two bodies are attracted to each
other and is related to the product of their masses but inversely proportional as
a square of their distance.
F = Gm1m2/r2
, where G is Newton's gravitational constant. A Java programmer
gets the wrong answer with the formula
F = G * mass1 * mass2 / r * r;
What is the error?