hi i need to catch and try exceptions , one for int and one for an array out of bounds i dont undertand how my code is'nt working for array out of bounds heres my code
import java.util.* ;
public class ExceptionHomewo rk
{
Scanner scan ;
int data;
int slot;
int[] value;
/**
* Constructor for objects of class
* ExceptionHomewo rk
*/
public ExceptionHomewo rk()
{
scan = new Scanner( System.in );
data=0;
slot=0 ;
value = new int[10];
}
/**
* This is the method you must change by adding
* try-catch blocks
*
*/
public void sampleMethod() throws ArrayIndexOutOf BoundsException
{
System.out.prin t("Enter the data: ");
data = scan.nextInt();
System.out.prin t("Enter the array index: ");
slot = scan.nextInt();
value[slot] = data;
try{
for(slot =0;slot <10;slot++){
value[slot] = slot;
}
System.out.prin tln(value);
}
catch(ArrayInde xOutOfBoundsExc eption e){
//printed just to inform that we have entered the catch block
System.out.prin tln("Oops, we went to far, better go back to 0!");
}
finally{
System.out.prin tln(value);
//method call to continue program
}
}
}
heres my driver
public class ExceptionHomewo rkDriver
{
public static void main ( String [] args)
{
ExceptionHomewo rk exHmwk = new ExceptionHomewo rk();
exHmwk.sampleMe thod();
System.out.prin tln("Good By");
}
}
import java.util.* ;
public class ExceptionHomewo rk
{
Scanner scan ;
int data;
int slot;
int[] value;
/**
* Constructor for objects of class
* ExceptionHomewo rk
*/
public ExceptionHomewo rk()
{
scan = new Scanner( System.in );
data=0;
slot=0 ;
value = new int[10];
}
/**
* This is the method you must change by adding
* try-catch blocks
*
*/
public void sampleMethod() throws ArrayIndexOutOf BoundsException
{
System.out.prin t("Enter the data: ");
data = scan.nextInt();
System.out.prin t("Enter the array index: ");
slot = scan.nextInt();
value[slot] = data;
try{
for(slot =0;slot <10;slot++){
value[slot] = slot;
}
System.out.prin tln(value);
}
catch(ArrayInde xOutOfBoundsExc eption e){
//printed just to inform that we have entered the catch block
System.out.prin tln("Oops, we went to far, better go back to 0!");
}
finally{
System.out.prin tln(value);
//method call to continue program
}
}
}
heres my driver
public class ExceptionHomewo rkDriver
{
public static void main ( String [] args)
{
ExceptionHomewo rk exHmwk = new ExceptionHomewo rk();
exHmwk.sampleMe thod();
System.out.prin tln("Good By");
}
}
Comment