|
- Problem 1:
- Rewrite the following program segment as a single if-else statement.
if (n < 5)
x = x + n;
if (n >= 5)
x = x - n;
- Problem 2:
- Rewrite the following program segment using nested conditional statements.
if (p > 0) g.drawString("positive", 50, 50);
if (p == 0) g.drawString("zero", 50, 50);
if (p < 0) g.drawString("negative", 50, 50);
- Problem 3:
- Find the error in the following if-statement and correct it.
if (x && y == 0)
g.drawString("That's the origin.", 50, 50);
- Problem 4:
- Explain what the following program segment does, and then correct it so that it does what it was meant to do. (Hint: See page 205 of the textbook, and add a pair of braces { and }.)
if (x == y)
if (x == 0)
g.drawString("x and y are both zero.", 50, 50);
else
g.drawString("x and y are not equal.", 50, 50);
- Problem 5:
- In Java, what is the value of y if
y = "2+2" + 2;
- Problem 6:
- In Java, if x is an integer, and I wish to convert it to a string, what is wrong with the following line?
x = "" + x;
- Problem 7:
- What is the output of the following program segment?
a = 1; b = 5;
while (a > 0)
{ a = a + b;
b = b - 3;
System.out.println(a + " and " + b);
}
- Problem 8:
- What is the output from the following program segment?
for (i = 2; i <= 5; i++)
for (j = 5; j > i; j = j-1);
System.out.println(i + " and " + j);
- Problem 9:
- The following program segment prints out the first 10 odd integers.
n = 10; i = 0;
while (i <= 2*n - 1)
{ i = i + 2;
System.out.println(i);
}
What would be the output if we had forgotten to include the two braces { and }?
- Problem 10:
- Find three syntax errors in the following Java program.
public class Incorrect
{
public static void main(String[] args)
{ x = 3;
System.out.println("the value of x is" x),
System.out.println("is that OK?);
}
- Problem 11:
- Write a program segment that declares and constructs an array, and then uses a loop to initialize the array with the following numbers.
-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5
- Problem 12:
- An array called numbers is declared and constructed by the following line.
int[] numbers = new int[10]
Suppose that this array is then initialized with random integers. Describe as best you can what the following program segment does. For example, after each loop around the for-loop, how would you describe the value of x? Also, how would you describe the output of this code?
int x = numbers[0];
for (i = 1; i < 10; i++)
if (numbers[i] >= x)
x = numbers[i];
System.out.println(x);
|
|