Laboratory 7: Assignment Cover Sheet Name Date Section Fill in the

Laboratory 7: Assignment Cover Sheet
___________________________________________________________
Name __________________________________________ Date _______________________
Section _________________________________________
Fill in the following table showing which exercises have been assigned for each lesson and check
what you are to submit: (1) lab sheets, (2) listings of output files, and/or (3) listings of programs.
Your instructor or teaching assistant (TA) can use the Completed column for grading purposes.
Activities
Prelab
Review
Prelab Assignment
Inlab
Lesson 7-1: Check Prelab Exercises
Lesson 7-2: Multi-Way Branching
Lesson 7-3: Additional Control
Structures
Lesson 7-4: Exception Handling
Lesson 7-5: Debugging
Postlab
Assigned: Check or
list exercise numbers
Submit
(1)
(2)
(3)
Completed
Laboratory 7: Prelab Assignment
___________________________________________________________
Name __________________________________________ Date _______________________
Section _________________________________________
Read program Loops carefully and answer Exercises 1 and 2.
_____________________________________________________________________________________
// Application Loops demonstrates various looping structures
import java.io.*;
import java.util.Scanner;
public class Loops
{
public static Scanner inData;
public static void main(String[] args) throws IOException
{
inData = new Scanner(new FileReader("Loop.dat"));
int value;
// while loop
int counter = 1;
int sum = 0;
while (counter <= 4)
{
value = inData.nextInt();
sum = sum + value;
counter++;
}
System.out.println(sum);
// do loop
counter = 1;
sum = 0;
do
{
value = inData.nextInt();
sum = sum + value;
counter++;
} while (counter <= 4);
System.out.println(sum);
// for loop
sum = 0;
for (counter = 1; counter <= 4; counter++)
{
value = inData.nextInt();
sum = sum + value;
}
System.out.println(sum);
}
}
_____________________________________________________________________________________
Exercise 1: If file Loop.dat contains the following values (one per line), what is printed?
10 20 30 40 10 20 30 40 10 20 30 40
Answer:
100
100
100
Exercise 2: Which of these loops are pretest loops? Which are posttest loops?
Answer:
Pretest lops:
while (counter <= 4)
for (counter = 1; counter <= 4; counter++)
posttest loops:
do
{
} while (counter <= 4);
Examine program Switches and answer Exercises 3 and 4.
_____________________________________________________________________________________
// Application Switches demonstrates the use of the Switch
// statement.
import java.util.Scanner;
public class Switches
{
public static void main(String[] args)
{
char code;
int answer;
int one;
int two;
String inputString;
boolean quit = false;
Scanner inLine = new Scanner(System.in);
do
{
inputString = inLine.nextLine();
code = inputString.charAt(0);
if (code != 'Q')
{
inputString = inputString.substring(1,
inputString.length());
Scanner string = new Scanner(inputString);
one = string.nextInt();
two = string.nextInt();
switch (code)
{
case 'A' : answer = (one + two);
System.out.println(one + " + " + two
+ " is " + answer);
break;
case 'S' : answer = (one - two);
System.out.println(one + " - " + two
+ " is " + answer);
break;
case 'M' : answer = (one * two);
System.out.println(one + " * " + two
+ " is " + answer);
break;
case 'D' : answer = (one / two);
System.out.println(one + " / " + two
+ " is " + answer);
break;
}
}
else
quit = true;
} while (!quit);
}
}
_____________________________________________________________________________________
Exercise 3: There is no prompt for input in this application. Write the prompt.
Answer: here is the modified program:
// Application Switches demonstrates the use of the Switch
// statement.
import java.util.Scanner;
public class Switches
{
public static void main(String[] args)
{
char code;
int answer;
int one;
int two;
String inputString;
boolean quit = false;
Scanner inLine = new Scanner(System.in);
do
{
System.out.println("Menu: Choose the appropriate code.");
System.out.println(" Q: Quit");
System.out.println(" A: Add");
System.out.println(" S: Substract");
System.out.println(" M: Multiply");
System.out.println(" D: Integer division");
System.out.println("Use uppercase letters only, followed "+ "by two integer operands.");
inputString = inLine.nextLine();
code = inputString.charAt(0);
if (code != 'Q')
{
inputString = inputString.substring(1,
inputString.length());
Scanner string = new Scanner(inputString);
one = string.nextInt();
two = string.nextInt();
switch (code)
{
case 'A' : answer = (one + two);
System.out.println(one + " + " + two
+ " is " + answer);
break;
case 'S' : answer = (one - two);
System.out.println(one + " - " + two
+ " is " + answer);
break;
case 'M' : answer = (one * two);
System.out.println(one + " * " + two
+ " is " + answer);
break;
case 'D' : answer = (one / two);
System.out.println(one + " / " + two
+ " is " + answer);
break;
}
}
else
quit = true;
} while (!quit);
}
}
Exercise 4: What is printed if the following values are entered?
A
5
–7
A
–5
–8
S
7
7
S
8
–8
M
8
–8
D
8
8
Q
Answer:
A
5
–7
5 + -7 is -2
A
–5
–8
-5 + -8 is -13
S
7
7
7 - 7 is 0
S
8
–8
8 - -8 is 16
M
8
–8
8 * -8 is -64
D
8
8
8 / 8 is 1
Q
No output, Program quits
Exercise 5: What happens if the Q to quit is entered as a lowercase letter?
Answer:
Exception in thread "main" java.util.NoSuchElementException is thrown
Lesson 7-1: Check Prelab Exercises
___________________________________________________________
Name __________________________________________ Date _______________________
Section _________________________________________
Exercise 1: Run program Loops and check your answers. Were your answers correct? If not, do you
understand your mistakes?
Answer: Yes, the answers were correct. Yes I understand the mistakes
Exercise 2: while loops and for loops are pretest loops; the loop body is not executed if the ending
condition is true initially. do loops are posttest loops; their bodies are always executed at least once.
Answer: Yes, it is correct.
Exercise 3:
_____________________________________________________________________________________
System.out.println("Menu: Choose the appropriate code.")
System.out.println(" Q: Quit");
System.out.println(" A: Add");
System.out.println(" S: Substract");
System.out.println(" M: Multiply");
System.out.println(" D: Integer division");
System.out.println("Use uppercase letters only, followed "
+ by two integer operands.");
_____________________________________________________________________________________
Answer: Prompt added.
Exercise 4: Run program Switches to check your answers. Were your answers correct? If not, do you
understand your mistakes?
Answer: Yes, the answers were correct. Yes I understand the mistakes
Exercise 5: If a lowercase Q is entered, the if-then clause is executed. The screen freezes waiting for you to
enter more values.
Answer:
No, the exception was thrown. Here is the screenshot:
Lesson 7-2: Multi-Way Branching
___________________________________________________________
Name __________________________________________ Date _______________________
Section _________________________________________
Exercise 1: As Prelab Exercise 5 demonstrated, application Switches is not very robust. Add the code
necessary to allow the program to work properly with both lowercase and uppercase versions of all the
input letters. Run your program with the same data, but key the letters as lowercase.
Answer:
Replace following statement
inputString = inLine.nextLine();
with
inputString = (inLine.nextLine()).toUpperCase();
Now it works with lowercase and upper case letters
Exercise 2: Application Switches is still not very robust. Add a default case to the switch statement that
prints an error message that states that the calculation was not preformed. Test your program with the same
data set, but add several letters that are not correct. Compile and run your program. Show your output.
Replace old switch block with this one:
switch (code)
{
case 'A' : answer = (one + two);
System.out.println(one + " + " + two
+ " is " + answer);
break;
case 'S' : answer = (one - two);
System.out.println(one + " - " + two
+ " is " + answer);
break;
case 'M' : answer = (one * two);
System.out.println(one + " * " + two
+ " is " + answer);
break;
case 'D' : answer = (one / two);
System.out.println(one + " / " + two
+ " is " + answer);
break;
default:
System.out.println("Error: The calculation was not
preformed");
}
A
5
–7
5 + -7 is -2
A
–5
–8
-5 + -8 is -13
S
7
7
7 - 7 is 0
S
8
–8
8 - -8 is 16
M
8
–8
8 * -8 is -64
D
8
8
8 / 8 is 1
Q
No output, Program quits
F
4
4
h
5
6
Z
2
3
Error: The calculation
was not preformed
Error: The calculation
was not preformed
Error: The calculation
was not preformed
Exercise 3: Class CountPunct is the shell of an application that counts all the punctuation marks in a file.
_____________________________________________________________________________________
// Application CountPunct counts punctuation marks in a file
import java.util.Scanner;
import java.io.*;
public class CountPunct
{
public static void main(String[] args)
throws FileNotFoundException
{
FileReader file = new FileReader("Punct.dat");
Scanner inFile = new Scanner(file);
String line;
char symbol;
int periodCt = 0;
int commaCt = 0;
int questionCt = 0;
int colonCt = 0;
int semicolonCt = 0;
int count;
while (inFile.hasNextLine()) // Loop until end of data
{
line = inFile.nextLine();
count = 0;
while (count < line.length())
{ // Loop until end of line
symbol = line.charAt(count);
// TO BE FILLED IN: count punctuation marks
count++;
}
}
// TO BE FILLED IN: output
}
}
_____________________________________________________________________________________
Fill in the missing code and run your program.
Number of periods:
Number of commas:
Number of question marks:
Number of colons:
Number of semicolons:
Number
Number
Number
Number
Number
of
of
of
of
of
periods: 6
commas: 3
question marks:3
colons: 4
semicolons: 2
Answer:
// Application CountPunct counts punctuation marks in a file
import java.util.Scanner;
import java.io.*;
public class CountPunct
{
public static void main(String[] args)
throws FileNotFoundException
{
FileReader file = new FileReader("Punct.dat");
Scanner inFile = new Scanner(file);
String line;
char symbol;
int periodCt = 0;
int commaCt = 0;
int questionCt = 0;
int colonCt = 0;
int semicolonCt = 0;
int count;
while (inFile.hasNextLine()) // Loop until end of data
{
line = inFile.nextLine();
count = 0;
while (count < line.length())
{ // Loop until end of line
symbol = line.charAt(count);
// TO BE FILLED IN: count punctuation marks
if(symbol=='.')periodCt++;
else if(symbol==',')commaCt++;
else if(symbol=='?')questionCt++;
else if(symbol==':')colonCt++;
else if(symbol==';')semicolonCt++;
count++;
}
}
// TO BE FILLED IN: output
System.out.println("Number of periods: "+periodCt);
System.out.println("Number of commas: "+commaCt);
System.out.println("Number of question marks:"+questionCt);
System.out.println("Number of colons: "+colonCt);
System.out.println("Number of semicolons: "+semicolonCt);
}
}
Exercise 4: Add the code necessary for application CountPunct to count blanks as well. How many blanks
are there in file Punct.dat? If you did not get 11, go back and check your program.
blanks are in file Punct.dat: 11
// Application CountPunct counts punctuation marks in a file
import java.util.Scanner;
import java.io.*;
public class CountPunct
{
public static void main(String[] args)
throws FileNotFoundException
{
FileReader file = new FileReader("Punct.dat");
Scanner inFile = new Scanner(file);
String line;
char symbol;
int periodCt = 0;
int commaCt = 0;
int questionCt = 0;
int colonCt = 0;
int semicolonCt = 0;
int spaceCt=0;
int count;
while (inFile.hasNextLine()) // Loop until end of data
{
line = inFile.nextLine();
count = 0;
while (count < line.length())
{ // Loop until end of line
symbol = line.charAt(count);
// TO BE FILLED IN: count punctuation marks
if(symbol=='.')periodCt++;
else if(symbol==',')commaCt++;
else if(symbol=='?')questionCt++;
else if(symbol==':')colonCt++;
else if(symbol==';')semicolonCt++;
else if(symbol==' ')spaceCt++;
count++;
}
}
// TO BE FILLED IN: output
System.out.println("Number of periods: "+periodCt);
System.out.println("Number of commas: "+commaCt);
System.out.println("Number of question marks:"+questionCt);
System.out.println("Number of colons: "+colonCt);
System.out.println("Number of semicolons: "+semicolonCt);
System.out.println("Number of spaces: "+spaceCt);
}
}
Lesson 7-3: Additional Control Structures
___________________________________________________________
Name __________________________________________ Date _______________________
Section _________________________________________
Use program Looping for Exercises 1, 2, and 3. This program reads and sums exactly 10 integers and then
reads and sums integers until a negative value is read.
_____________________________________________________________________________________
// Application Looping uses a count-controlled loop to read
// and sum 10 integer values and an event-controlled loop to
// read and sum values until a negative value is found.
import java.io.*;
import java.util.Scanner;
public class Looping
{
public static Scanner inData;
public static void main(String[] args) throws IOException
{
inData = new Scanner(new FileReader("Looping.dat"));
int value;
int counter;
int sum;
counter = 1;
sum = 0;
while (counter <= 10)
{// Ten values read and summed
value = inData.nextInt();
sum = sum + value;
counter++;
}
System.out.println("The first sum is " + sum);
value = inData.nextInt();
sum = 0;
while (value >= 0)
{// Values are read and summed until a negative is read
sum = sum + value;
value = inData.nextInt();
}
System.out.println("The second sum is " + sum);
}
}
_____________________________________________________________________________________
Exercise 1: Compile and run program Looping.
The first sum is 230
The second sum is 260
Exercise 2: Program Looping contains two loops implemented with while statements.Rewrite program
Looping, replacing the while statements with do statements.
// Application Looping uses a count-controlled loop to read
// and sum 10 integer values and an event-controlled loop to
// read and sum values until a negative value is found.
import java.io.*;
import java.util.Scanner;
public class Looping
{
public static Scanner inData;
public static void main(String[] args) throws IOException
{
inData = new Scanner(new FileReader("Looping.dat"));
int value;
int counter;
int sum;
counter = 1;
sum = 0;
do
{// Ten values read and summed
value = inData.nextInt();
sum = sum + value;
counter++;
}while (counter <= 10);
System.out.println("The first sum is " + sum);
value = inData.nextInt();
sum = 0;
do
{// Values are read and summed until a negative is read
sum = sum + value;
value = inData.nextInt();
}while (value >= 0);
System.out.println("The second sum is " + sum);
}
}
The first sum is 230
The second sum is 260
Exercise 3: Can program Looping be rewritten using a for statement for each loop?
Explain.
Answer: Yes, it can be rewritten using for loop for each loop:
First while loop can be rewritten using for loop like this:
for(;counter <= 10;counter++)
Second loop can be rewtritten using for loop as
for(;value >= 0;)
Rewrite program Looping using a for statement to implement the count-controlledloop.
// Application Looping uses a count-controlled loop to read
// and sum 10 integer values and an event-controlled loop to
// read and sum values until a negative value is found.
import java.io.*;
import java.util.Scanner;
public class Looping
{
public static Scanner inData;
public static void main(String[] args) throws IOException
{
inData = new Scanner(new FileReader("Looping.dat"));
int value;
int counter;
int sum;
counter = 1;
sum = 0;
for(;counter <= 10;counter++)
{// Ten values read and summed
value = inData.nextInt();
sum = sum + value;
}
System.out.println("The first sum is " + sum);
value = inData.nextInt();
sum = 0;
//while (value >= 0)
for(;value >= 0;)
{// Values are read and summed until a negative is read
sum = sum + value;
value = inData.nextInt();
}
System.out.println("The second sum is " + sum);
}
}
The first sum is 230
The second sum is 260
Exercise 4: Rerun your program using data file Looping.d2. Describe what happens.
If an error condition was generated, correct your program and rerun the program.
No error
// Application Looping uses a count-controlled loop to read
// and sum 10 integer values and an event-controlled loop to
// read and sum values until a negative value is found.
import java.io.*;
import java.util.Scanner;
public class Looping
{
public static Scanner inData;
public static void main(String[] args) throws IOException
{
inData = new Scanner(new FileReader("Looping.dat"));
int value;
int counter;
int sum;
counter = 1;
sum = 0;
for(;counter <= 10;counter++)
{// Ten values read and summed
value = inData.nextInt();
sum = sum + value;
}
System.out.println("The first sum is " + sum);
value = inData.nextInt();
sum = 0;
//while (value >= 0)
for(;value >= 0;)
{// Values are read and summed until a negative is read
sum = sum + value;
value = inData.nextInt();
}
System.out.println("The second sum is " + sum);
}
}
The first sum is 16522
The second sum is 0
Exercise 5: Application CountPunct has two while loops. Replace the first with a do statement and the
second with a for statement. You must add an assumption to the application, what is it? Rerun your
application with the same data.
// Application CountPunct counts punctuation marks in a file
import java.util.Scanner;
import java.io.*;
public class CountPunct
{
public static void main(String[] args)
throws FileNotFoundException
{
FileReader file = new FileReader("Punct.dat");
Scanner inFile = new Scanner(file);
String line;
char symbol;
int periodCt = 0;
int commaCt = 0;
int questionCt = 0;
int colonCt = 0;
int semicolonCt = 0;
int spaceCt=0;
int count;
do
{
line = inFile.nextLine();
count = 0;
for (;count < line.length();)
{ // Loop until end of line
symbol = line.charAt(count);
// TO BE FILLED IN: count punctuation marks
if(symbol=='.')periodCt++;
else if(symbol==',')commaCt++;
else if(symbol=='?')questionCt++;
else if(symbol==':')colonCt++;
else if(symbol==';')semicolonCt++;
else if(symbol==' ')spaceCt++;
count++;
}
}while (inFile.hasNextLine()); // Loop until end of data
// TO BE FILLED IN: output
System.out.println("Number of periods: "+periodCt);
System.out.println("Number of commas: "+commaCt);
System.out.println("Number of question marks:"+questionCt);
System.out.println("Number of colons: "+colonCt);
System.out.println("Number of semicolons: "+semicolonCt);
System.out.println("Number of spaces: "+spaceCt);
}
}
Assumption is that file Punct.dat is having at least one line or the code will throw en exception
Lesson 7-4: Exception Handling
___________________________________________________________
Name __________________________________________ Date _______________________
Section _________________________________________
Exercise 1: In Exercise 1 in Lesson 7-2, we pointed out that class Switches was not very robust. You were
asked in Exercise 2 to use the default case in the switch statement to handle the case of incorrect input data.
Rewrite this solution so that an object of an exception class is thrown on the default case. Compile and run
your solution. Compare your output with the output in Exercise 2. Were they the same?
// Application Switches demonstrates the use of the Switch
// statement.
import java.util.Scanner;
public class Switches
{
public static void main(String[] args) throws Exception
{
char code;
int answer;
int one;
int two;
String inputString;
boolean quit = false;
Scanner inLine = new Scanner(System.in);
do
{
System.out.println("Menu: Choose the appropriate code.");
System.out.println(" Q: Quit");
System.out.println(" A: Add");
System.out.println(" S: Substract");
System.out.println(" M: Multiply");
System.out.println(" D: Integer division");
System.out.println("Use uppercase letters only, followed "+ "by two integer operands.");
inputString = (inLine.nextLine()).toUpperCase();
code = inputString.charAt(0);
if (code != 'Q')
{
inputString = inputString.substring(1,
inputString.length());
Scanner string = new Scanner(inputString);
one = string.nextInt();
two = string.nextInt();
switch (code)
{
case 'A' : answer = (one + two);
System.out.println(one + "
+ " + two
+
"
is
"
+
answer);
break;
case 'S' : answer = (one - two);
System.out.println(one + "
- " + two
+
"
is
"
+
answer);
break;
case 'M' : answer = (one * two);
System.out.println(one + "
* " + two
+
"
is
"
+
answer);
break;
case 'D' : answer = (one / two);
System.out.println(one + "
/ " + two
+
"
is
"
+
answer);
break;
default:
throw new Exception("Error: The calculation was not preformed");
}
}
else
quit = true;
} while (!quit);
}
}
Yes the result were same.
Exercise 2: Go through the classes in this lesson and count how many of them could throw an IOException.
How many are there? What is the common theme in these applications?
Exercises 3 through 7 use the following application shell.
_____________________________________________________________________________________
import java.io.*;
import java.util.Scanner;
public class Exceptions
{
static Scanner inFile;
public static void main(String[] args) throws IOException
{
int fileTry = 0;
String fileName;
Scanner inName = new Scanner(System.in);
System.out.println("Enter file name");
fileName = inName.nextLine();
boolean fileOk;
do
{
fileOk = false;
try
{
// TO BE FILLED IN: Exercise 3
}
catch(FileNotFoundException error)
{
// TO BE FILLED IN: Exercise 4
}
} while (!fileOk && fileTry < 4);
PrintWriter outFile =
new PrintWriter(new FileWriter("outData.dat"));
if ( /* TO BE FILLED IN: Exercise 5 */ )
{
int numDays = 0;
double average;
double inches = 0.0;
double total = 0.0;
while (inFile.hasNextFloat())
{
inches = inFile.nextFloat();
total = total + inches;
outFile.println(inches);
numDays++;
}
if (numDays == 0)
System.out.println("Average cannot be computed " +
" for 0 days.");
else
{
average = total / numDays;
outFile.println("The average rainfall over " +
numDays + " days is " + average);
}
inFile.close();
}
else
// TO BE FILLED IN: Exercise 5
outFile.close();
}
}
_____________________________________________________________________________________
Each of the applications has set the file name as a literal. If the file cannot be found, the program crashes.
Class Exceptions lets the user input the file name from the keyboard. If the file cannot be found, the user is
prompted to reenter the file name. The user gets four tries to enter the name correctly before the application
quits without processing the data. The application itself is the rainfall-averaging program.
import java.io.*;
import java.util.Scanner;
public class Exceptions
{
static Scanner inFile;
public static void main(String[] args) throws IOException
{
int fileTry = 0;
String fileName;
Scanner inName = new Scanner(System.in);
System.out.println("Enter file name");
fileName = inName.nextLine();
boolean fileOk;
double value;
int counter;
double sum;
do
{
fileOk = false;
try
{
inFile = new Scanner(new FileReader(fileName));
fileOk=true;
}
catch(FileNotFoundException error)
{
System.out.println("Enter file name");
fileName = inName.nextLine();
fileTry++;
}
} while (!fileOk && fileTry < 4);
PrintWriter outFile =
new PrintWriter(new FileWriter("outData.dat"));
if ( outFile!=null )
{
int numDays = 0;
double average;
double inches = 0.0;
double total = 0.0;
while (inFile.hasNextFloat())
{
inches = inFile.nextFloat();
total = total + inches;
outFile.println(inches);
numDays++;
}
if (numDays == 0)
System.out.println("Average cannot be computed " +
" for 0
days.");
else
{
average = total / numDays;
outFile.println("The average rainfall over " +
numDays + " days is " + average);
}
inFile.close();
}
else
// TO BE FILLED IN: Exercise 5
outFile.close();
}
}
Exercise 3: Fill in the try portion in which the Scanner is instantiated and fileOK is set to true.
try
{
inFile = new Scanner(new FileReader(fileName));
fileOk=true;
}
catch(FileNotFoundException error)
{
System.out.println("Enter file name");
fileName = inName.nextLine();
fileTry++;
}
Exercise 4: Fill in the catch portion in which the user is prompted to reenter the file name, the file name is
read, and fileTry is incremented.
try
{
inFile = new Scanner(new FileReader(fileName));
fileOk=true;
}
catch(FileNotFoundException error)
{
System.out.println("Enter file name");
fileName = inName.nextLine();
fileTry++;
}
Exercise 5: Fill in the if expression so that the average is calculated or an error message is written on the
output file.
if ( outFile!=null )
Exercise 6: Run the application using file inData.dat. What is printed?
1.1883
Exercise 7: Run the application using the wrong file name 4 times. What is printed?
Exception is thrown
Lesson 7-5: Debugging
___________________________________________________________
Name __________________________________________ Date _______________________
Section _________________________________________
Exercise 1: Program Bugs is supposed to sum the first ten values on a file and the second ten values on a
file. The second ten values are a duplicate of the first ten, so the answers should be the same. The program
checks to be sure that the file has been found and halts execution if the file is not found. Program Bugs
compiles, says that the file cannot be found, but then crashes. Can you find the problem? Describe it.
It gives the following output
Bugs.dat not found
Exception in thread "main" java.lang.NullPointerException
at Bugs.main(Bugs.java:30)
Java Result: 1
To correct this error, we need to put break statement ij switch statement after case 1: statement
Exercise 2: Correct the problem and rerun the program. The file cannot be found, but now the program
halts correctly. Correct the name of the file and rerun the program.
// Application Bugs demonstrates various looping structures.
import java.io.*;
import java.util.Scanner;
public class Bugs
{
public static Scanner inData;
public static void main(String[] args) throws IOException
{
int fileFound;
try
{
inData = new Scanner(new FileReader("Bug.dat"));
fileFound = 1;
}
catch (IOException exception)
{
fileFound = 2;
}
int value;
switch (fileFound)
{
case 2 : System.out.println("Bugs.dat not found"); break;
case 1 :
// do loop
int counter = 1;
int sum = 0;
do
{
value = inData.nextInt();
sum = sum + value;
} while (counter <= 10);
System.out.println(sum);
// for loop
sum = 0;
for (counter = 1; counter <= 10; counter++)
{
value = inData.nextInt();
sum = sum + value;
counter++;
}
System.out.println(sum);
}
}
}
Exercise 3: What—the program crashes again? Back to the drawing board. Describe the next error you
find. Correct the program and run it again.
It now throws
Exception in thread "main" java.util.NoSuchElementException
Added statement
counter++;
inside
do
{
value = inData.nextDouble();
sum = sum + value;
counter++;
} while (counter <= 10);
Exercise 4: Now you are getting output, but the answer is wrong for the second sum. When you find this
last error, describe it, correct it, and rerun the program. What are the correct totals?
There was an extra counter++; statement inside for loop
Here is final program:
// Application Bugs demonstrates various looping structures.
import java.io.*;
import java.util.Scanner;
public class Bugs
{
public static Scanner inData;
public static void main(String[] args) throws IOException
{
int fileFound;
try
{
inData = new Scanner(new FileReader("Bug.dat"));
fileFound = 1;
}
catch (IOException exception)
{
fileFound = 2;
}
double value;
switch (fileFound)
{
case 2 : System.out.println("Bugs.dat not found"); break;
case 1 :
// do loop
int counter = 1;
double sum = 0;
do
{
value = inData.nextDouble();
sum = sum + value;
counter++;
} while (counter <= 10);
System.out.println(sum);
// for loop
sum = 0;
for (counter = 1; counter <= 10; counter++)
{
value = inData.nextInt();
sum = sum + value;
}
System.out.println(sum);
}
}
}