//DebugTwelve3; Chapter 12; Java Programming; Joyce Farrell; 8th Edition //error
ID: 3675941 • Letter: #
Question
//DebugTwelve3; Chapter 12; Java Programming; Joyce Farrell; 8th Edition
//error to be fixed
1 // Catch exceptions for array index out of bounds
2 // or dividing by 0
3 import javax.swing.*;
4 public class DebugTwelve3
5 {
6 public static void main(String[] args)
7 {
8 String inStr;
9 int num, result;
10 int[] array = {12, 4, 6, 8};
11 inStr = JOptionPane.showInputDialog(null, "Enter a number ");
12 num = Integer.parse(inStr);
13 try
14 {
15 for(int x = 0; x < array.length; ++x)
16 {
17 result = array[x] / num;
18 JOptionPane.showMessageDialog(null, "Result of division is " + result);
19 result = array[num];
20 JOptionPane.showMessageDialog(null, "Result accessing array is " + result);
21 }
22 }
23 catch(ArithmeticException error)
24 {
25 JOptionPane.showMessageDialog(null, "Arithmetic error - division by 0");
26 }
27 catch(IndexException error)
28 {
29 JOptionPane.showMessageDialog(null, "Index error - subscript out of range");
30 }
31 }
32 }
Explanation / Answer
import javax.swing.*;
public class HelloWorld{
public static void main(String []args){
String inStr;
int num, result;
int[] array = {12, 4, 6, 8};
inStr = JOptionPane.showInputDialog(null, "Enter a number ");
num = Integer.parseInt(inStr);
try
{
for(int x = 0; x < array.length; ++x)
{
result = array[x] / num;
JOptionPane.showMessageDialog(null, "Result of division is " + result);
result = array[num];
JOptionPane.showMessageDialog(null, "Result accessing array is " + result);
}
}
catch(ArithmeticException error)
{
JOptionPane.showMessageDialog(null, "Arithmetic error - division by 0");
}
catch(ArrayIndexOutOfBoundsException error)
{
JOptionPane.showMessageDialog(null, "Index error - subscript out of range");
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.