// DebuggingPractice.java
//
// The following code is very "buggy" -- for each
loop you should form a hypothesis as to
// what
is causing the error and suggest how it might be corrected
class
DebuggingPractice {
public static
void main(String[] args)
{
//
*********************************** 1 *******************************
// The
following loop should sum the first 5 positive integers
// (1 + 2 + 3 + 4 + 5 = 15) but it
gives no output at all. What's wrong?
int j = 1, sum = 0;
while (j
<= 5);
{
sum =
sum + j;
j++;
}
System.out.println("1)
The sum is: " + sum);
// *********************************
2 *********************************
// The
following for loop should also sum the first 5 positive integers but
// it prints the incorrect sum. What does it print? How should you fix it?
for (j = 1,
sum = 0; j < 5; j++)
sum =
sum + j;
System.out.println("2)
The sum is: " + sum);
// *********************************
3 *********************************
// The
following for loop should print the odd integers between 1 and 100
// What's
wrong with it?
for (j = 1;
j != 100; j = j + 2)
System.out.println(j);
// *********************************
4 *********************************
// This loop
should count the uppercase Xs in the String test (4)
// but it prints the answer is
3. What's wrong with it?
int count = 0;
String test = "XTHIS XX is a X
test to count upper case x's";
for(int i = 1; i
< test.length(); i++)
if (test.charAt(i) == 'X')
count++;
System.out.println(test +
"\ncontains " + count + " Xs ");
// *********************************
5 *********************************
// This
loop should also count the uppercase Xs in test but instead it
// crashes, displaying an IndexOutOfBoundsException.
What's up?
count = 0;
for(int i = 0; i
<= test.length(); i++)
if (test.charAt(i) == 'X')
count++;
System.out.println(test +
"\ncontains " + count + " Xs ");
// *********************************
5 *********************************
// This
loop should count the lowercase letters in a String but for the
// string below it reports there are
11 lowercase letters instead of 6. Why?
count = 0;
test =
"aBCdefgHIjk";
for(int i = 0; i
< test.length(); i++)
if (test.charAt(i) >= 'a' || test.charAt(i) <= 'z')
count++;
System.out.println(test +
"\ncontains " + count + " lowercase
letters ");
}
}