Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Lab8 Access Array Exercise Warmup Exercises A number of practice questions to help you prepare for doing this lab are provided in the file Lab7_warmup_exercises.pdf

Lab8 Access Array Exercise

Warmup Exercises

A number of practice questions to help you prepare for doing this lab are provided in the file

Lab7_warmup_exercises.pdf

Due Date and Demonstration

This Lab Exercise is worth 10 marks, and must be demonstrated to your lab instructor. See Blackboard for the

due date. Do not forget to do the Follow-Up Question and Activity!

The problem of this Lab Exercise is divided into six parts:

1. Lab Objectives

2. Description of the Problem

3. Required Output

4. Provided source code

5. Instructions

6. Problem-Solving Tips

7. Follow-Up Question and Activity

The program template represents a complete working Java program with one or more key lines of code

replaced with comments. Read the problem description and examine the sample output, then study the

template code. Using the problem-solving tips as a guide, replace the /* */ comments with Java code.

Compile and execute the program. Compare your output with the sample output provided. Then answer

the follow-up question. The source code for the template is provided for you.

Lab Objectives

This lab was designed to reinforce programming concepts from Chapter 11 (Exception Handling: A

Deeper Look) of Java How to Program: 10/e. In this lab, you will practice:

Using exception handling to determine valid inputs.

Using exception handling to write more robust and more fault-tolerant programs.

The follow-up activity also will give you practice:

Creating your own exception type and throwing exceptions of that type.

Description of the Problem

Write a program that allows a user to input integer values into a 10-element array and search the array.

The program should allow the user to retrieve values from the array by index or by specifying a value to

locate. The program should handle any exceptions that might arise when inputting values or accessing

array elements. The program should throw a NumberNotFoundException if a particular value cannot be

found in the array during a search. If an attempt is made to access an element outside the array bounds,

catch the ArrayIndexOutOfBoundsException and display an appropriate error message.

Required Output

==>sending array test1

Invalid number

==>sending array test2

Array out of bounds

==>sending array test3

==>index for: aaa

Invalid number

==>index for: 12

Number not found

==>index for: 4

4, index: 3

==>value for: aaa

Invalid number

==>value for: -1

Array out of bounds

==>value for: 5

index 5:6

Provided source Code

The following java code is provided in lab7.zip

- ArrayAccessIf.java

- ArrayAccessTest.java

- NumberNotFoundException.java

Instructions

The following is the recommended steps for this assignment:

- Create a package called lab7, and copy all the files from lab7.zip.

- Create ArrayAccess class that implements ArrayAccessIf.

- Implement the methods in ArrayAccess as described in ArrayAccessIf.

- Implement printing messages as per Required Output.

- If you are printing in try block, use System.out stream.

- If you are printing in catch block, ensure you use System.err stream.

- Run the provided ArrayAccessTest.java and compare with required result.

Problem-Solving Tips

1. When you search the array for a value, you should define a boolean value at the beginning of the try

block and initialize it to false. If the value is found in the array, set the boolean value to true. This will

help you determine whether you need to throw an exception due to a search key that is not found.

4. If you have any questions as you proceed, ask your lab instructor for assistance.

Follow-Up Activity

1. Create a copy of your project (highlight the project in Eclipse and ctrl-C ctrl-V), and in the copy, create

another exception class called DuplicateValueException that will be thrown if the user inputs a value

that already resides in the array. Modify the copy your lab exercise solution to use this new exception

class to indicate when a duplicate value is input, in which case an appropriate error message should be

printed. During your demonstration, your lab instructor may ask to see either the original solution, or

the modified copy

-------------------------------------------------------------------------------------------------------------------------------------

// Lab7_warmup_exercises.pdf

Lab Warmup Exercises

Use these warmup exercises to ease you into doing Lab7. Answers are provided at the end of the document.

Section A: Program Output

What is output by the following application?

1 public class Test

2 {

3 public static String lessThan100( int number ) throws Exception

4 {

5 if ( number >= 100 )

6 throw new Exception( "Number too large." );

7

8 return String.format( "The number %d is less than 100", number );

9 }

10

11 public static void main( String args[] )

12 {

13 try

14 {

15 System.out.println( lessThan100( 1 ) );

16 System.out.println( lessThan100( 22 ) );

17 System.out.println( lessThan100( 100 ) );

18 System.out.println( lessThan100( 11 ) );

19 }

20 catch( Exception exception )

21 {

22 System.out.println( exception.toString() );

23 }

24 } // end main method

25 } // end class Test

What is output by the following program?

1 public class Test

2 {

3 public static void method3() throws RuntimeException

4 {

5 throw new RuntimeException( "RuntimeException occurred in method3" );

6 }

7

8 public static void method2() throws RuntimeException

9 {

10 try

11 {

12 method3();

13 }

14 catch ( RuntimeException exception )

15 {

16 System.out.printf( "The following exception occurred in method2 %s ",

17 exception.toString() );

18 throw exception;

19 }

20 } // end method2

21

22 public static void method1() throws RuntimeException

23 {

24 try

25 {

26 method2();

27 }

28 catch ( RuntimeException exception )

29 {

30 System.out.printf( "The following exception occurred in method1 %s ",

31 exception.toString() );

32 throw exception;

33 }

34 } // end method1

35

36 public static void main( String args[] )

37 {

38 try

39 {

40 method1();

41 }

42 catch ( RuntimeException exception )

43 {

44 System.out.printf( "The following exception occurred in main %s ",

45 exception.toString() );

46 }

47 } // end main

48 } // end class test

What is output by the following program?

1 public class Test

2 {

3 public static String divide( int number1, int number2 )

4 {

5 return String.format( "%d divided by %d is %d",

6 number1, number2, ( number1 / number2 ) );

7 }

8

9 public static void main( String args[] )

10 {

11 try

12 {

13 System.out.println( divide( 4, 2 ) );

14 System.out.println( divide( 20, 5 ) );

15 System.out.println( divide( 100, 0 ) );

16 }

17 catch( Exception exception )

18 {

19 System.out.println( exception.toString() );

20 }

21 } // end main

22 } // end class Test

What is output by the following program if the user enters the values 3 and 4.7?

1 import javax.swing.JOptionPane;

2

3 public class Test

4 {

5 public static String sum( int num1, int num2 )

6 {

7 return String.format( "%d + %d = %d", num1, num2, ( num1 + num2 ) );

8 }

9

10 public static void main( String args[] )

11 {

12 int number1;

13 int number2;

14

15 try

16 {

17 number1 =

18 Integer.parseInt( JOptionPane.showInputDialog( "Enter an integer: " ) );

19

20 number2 = Integer.parseInt(

21 JOptionPane.showInputDialog( "Enter another integer: " ) );

22

23 System.out.println( sum( number1, number2 ) );

24 }

25 catch ( NumberFormatException numberFormatException )

26 {

27 System.out.println( numberFormatException.toString() );

28 }

29 } // end main method

30 } // end class Test

Section B: Correct the Code

Determine if there is an error in each of the following program segments. If there is an error, specify whether it is a logic error or a compilation error, circle the error in the program and write the corrected code in the space provided after each problem. If the code does not contain an error, write no error. [Note: There may be more than one error in each program segment.]

The following code segment should catch only NumberFormatExceptions and display an error message dialog if such an exception occurs:

1 catch ( Exception exception )

2 JOptionPane.showMessageDialog( this,

3 "A number format exception has occurred",

4 "Invalid Number Format", JOptionPane.ERROR_MESSAGE );

In the following code segment, assume that method1 can throw both NumberFormatExceptions and ArithmeticExceptions. The following code segment should provide appropriate exception handlers for each exception type and should display an appropriate error message dialog in each case:

1 try

2 method1();

3

4 catch ( NumberFormatException n, ArithmeticException a )

5 {

6 JOptionPane.showMessageDialog( this,

7 String.format( "The following exception occurred %s %s ",

8 n.toString(), a.toSting() ),

9 "Exception occurred", JOptionPane.ERROR_MESSAGE );

10 }

The following code segment should display an error message dialog if the user does not enter two integers:

1 try

2 {

3 int number1 =

4 Integer.parseInt( JOptionPane.showInputDialog( "Enter first integer:" ) );

5 int number2 =

6 Integer.parseInt( JOptionPane.showInputDialog( "Enter second integer:" ) );

7

8 JOptionPane.showMessageDialog( this, "The sum is: " + ( number1 + number2 ) );

9 }

Answers

Question 1. Your answer: The number 1 is less than 100

The number 22 is less than 100

java.lang.Exception: Number too large.

Question 2. Your answer: The following exception occurred in method2 java.lang.RuntimeException: RuntimeException occurred in method3

The following exception occurred in method1

java.lang.RuntimeException: RuntimeException occurred in method3

The following exception occurred in main

java.lang.RuntimeException: RuntimeException occurred in method3

Question 3. Your answer:

4 divided by 2 is 2

20 divided by 5 is 4

java.lang.ArithmeticException: / by zero

Question 4. Your answer:

java.lang.NumberFormatException: For input string: "4.7"

Question 5. Your answer:

1 catch ( NumberFormatException numberFormatException )

2 {

3 JOptionPane.showMessageDialog( this,

4 "A number format exception has occurred",

5 "Invalid Number Format", JOptionPane.ERROR_MESSAGE );

6 }

The catch handler should declare that it catches NumberFormatExceptions. This is a logic error.

The body of the catch handler must be enclosed in braces. This is a syntax error.

Question 6. Your answer:

1 try

2 {

3 method1();

4 }

5 catch ( NumberFormatException n )

6 {

7 JOptionPane.showMessageDialog( this,

8 "The following exception occurred " + n.toString(),

9 "Exception occurred", JOptionPane.ERROR_MESSAGE );

10 }

11 catch ( ArithmeticException a )

12 {

13 JOptionPane.showMessageDialog( this,

14 "The following exception occurred " + a.toString(),

15 "Exception occurred", JOptionPane.ERROR_MESSAGE );

16 }

The code in the try block must be enclosed in braces. This is a syntax error.

Each catch handler can handle only one type of exception, so each must be declared separately. This is a syntax error.

Question 7. Your answer:

1 try

2 {

3 int number1 =

4 Integer.parseInt( JOptionPane.showInputDialog( "Enter first integer:" ) );

5 int number2 =

6 Integer.parseInt( JOptionPane.showInputDialog( "Enter second integer:" ) );

7

8 JOptionPane.showMessageDialog( this, "The sum is: " + ( number1 + number2 ) );

9 }

10 catch ( NumberFormatException numberFormatException )

11 {

12 JOptionPane.showMessageDialog( this, numberFormatException,

13 "Exception occurred", JOptionPane.ERROR_MESSAGE );

14 }

A try block must be followed by either a catch handler or a finally block (as a minimum). This is a syntax error.

A catch handler must be declared to catch the NumberFormatException and display the error message dialog.

--------------------------------------------------------------------------------------------------------------------------------

//Learning Materials:

//ArrayAccessIf.java

package lab7;

public interface ArrayAccessIf {

/* TODO

* Create a try block in which the String array s[] gets converted to integer array array[].

* For String to Integer conversion, use Integer.parseInt(String s) function.

* Throw ArrayIndexOutOfBoundsException if the length of s[] is greater than 10.

* Needs to catch NumberFormatException and ArrayIndexOutOfBoundsException.

*/

public void initArray(String s[]);

/* TODO

* Create a try block to print out the index for the value given in String s.

*

* Write catch handlers that catch the two types of exceptions that the try

* block might throw (NumberFormatException and NumberNotFoundException), and

* print error messages as specified in the assignment.

*/

public void findIndexFor(String s);

/* TODO

* Create a try block to print out the value for the index given in String s.

*

* Write catch handlers that catch the two types of exceptions that the try

* block might throw (NumberFormatException and ArrayIndexOutOfBoundsException), and

* print error messages as specified in the assignment.

*/

public void findValueFor(String s);

} // End class ArrayAcessIf.java

//ArrayAcessTest.java

package lab7;

public class ArrayAccessTest {

public static void main(String args[]) {

ArrayAccess application = new ArrayAccess();

String test1[] = {"1","2","aaa","4","5","6","7","8","9","10"};

System.setErr(System.out); // to have an ordered output

System.out.println("==>sending array test1");

application.initArray(test1);

String test2[] = {"1","2","3","4","5","6","7","8","9","10","11"};

System.out.println("==>sending array test2");

application.initArray(test2);

String test3[] = {"1","2","3","4","5","6","7","8","9","10"};

System.out.println("==>sending array test3");

application.initArray(test3);

System.out.println("==>index for: "+test1[2]);

application.findIndexFor(test1[2]);

System.out.println("==>index for: 12");

application.findIndexFor("12");

System.out.println("==>index for: 4");

application.findIndexFor("4");

System.out.println("==>value for: "+test1[2]);

application.findValueFor(test1[2]);

System.out.println("==>value for: -1");

application.findValueFor("-1");

System.out.println("==>value for: 5");

application.findValueFor("5");

}

} // end class ArrayAccessTest

//NumberNotFoundException

package lab7;

public class NumberNotFoundException extends Exception {

private static final long serialVersionUID = 1L;

// no-argument constructor specifies default error message

public NumberNotFoundException() {

super( "Number not found in array" );

}

// constructor to allow customized error message

public NumberNotFoundException( String message ) {

super( message ); //

} // end class NumberNotFoundException

} // end class NumberNotFoundException

Instructions

The following is the recommended steps for this assignment:

- Create a package called lab7, and copy all the files from lab7.zip.

- Create ArrayAccess class that implements ArrayAccessIf.

- Implement the methods in ArrayAccess as described in ArrayAccessIf.

- Implement printing messages as per Required Output.

- If you are printing in try block, use System.out stream.

- If you are printing in catch block, ensure you use System.err stream.

- Run the provided ArrayAccessTest.java and compare with required result.

Problem-Solving Tips

1. When you search the array for a value, you should define a boolean value at the beginning of the try

block and initialize it to false. If the value is found in the array, set the boolean value to true. This will

help you determine whether you need to throw an exception due to a search key that is not found.

4. If you have any questions as you proceed, ask your lab instructor for assistance.

Follow-Up Activity

1. Create a copy of your project (highlight the project in Eclipse and ctrl-C ctrl-V), and in the copy, create

another exception class called DuplicateValueException that will be thrown if the user inputs a value

that already resides in the array. Modify the copy your lab exercise solution to use this new exception

class to indicate when a duplicate value is input, in which case an appropriate error message should be

printed. During your demonstration, your lab instructor may ask to see either the original solution, or

the modified copy

------------------------------------------------------------------------------------------------------------------------------------------------

've been getting many questions about the follow up activity, so I decided to send a reply to you all.

For the Follow Up Activity, you want to create a new project that is a copy of the first part of Lab 7. So you should have two projects, and submit two projects. Please ZIP both projects into one final ZIP file to upload to Blackboard, though.

Next, in your new copy of the project, create a new Exception subclass, called DuplicateValueException. You can copy the NumberNotFoundException to use as template.

In the initArray method, you'll need to modify the code to throw this new DuplicateValueException in the case the "user" attempts to insert a dupliate value into an array. This is the only method in ArrayAccess to modify for the follow up activity.

In the new copy of ArrayTest, you'll want to modify at least one of the test arrays, or add a new test array, which will attempt to load a duplicate value. You may want to create more than one to check loading a duplicate value in an otherwise ideal array (all numeric, correct size), and loading a duplicate value in an incorrect array, to see what errors are thrown in which order.

So in a nutshell:

Submit two java projects, in ONE zip file.

Ensure your name is on every folder in the zip, so when I unzip, I can find things easily.

No Junit, Javadoc, or UML is required (although commenting your code is always a good idea, and lets me know you authored the work and that you truly understand the code).

Part B has one new class, DuplicateValueException, a modified ArrayAccess.initArray method, and a modified ArrayTest file to properly test your work.

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Database Administrator Limited Edition

Authors: Martif Way

1st Edition

B0CGG89N8Z

More Books

Students also viewed these Databases questions

Question

We know how businesses are classified according to their function.

Answered: 1 week ago

Question

Provide examples of Dimensional Tables.

Answered: 1 week ago