Write a program in Java with arrays.
Answers
Explanation:
ArrayIndexOutOfBoundsException
//Java Program to demonstrate the case of.
//ArrayIndexOutOfBoundsException in a Java Array.
public class TestArrayException{
public static void main(String args[]){
int arr[]={50,60,70,80};
for(int i=0;i<=arr.length;i++){
System.out.println(arr[i]);
}
Algorithm:
- Accepting the elements of the Matrix using Scanner.
- Displaying the Matrix before processing it.
- Reversing each element of the Matrix by iterating over each element and reversing it by using the reverse method.
- Displaying the Matrix after processing it.
Program:
public class ReverseNumbersInArray {
static int[ ][ ] matrix = new int[3][4];
static void displayMatrix(String title) {
System.out.println(title);
for (int[ ] rows : matrix)
System.out.println(Arrays.toString(rows));
}
static int reverse(int number) {
return Integer.parseInt(new StringBuilder(number + "").reverse( ).toString( ));
}
public static void main(String[ ] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter elements of the Matrix (3 × 4) - ");
for (int[ ] rows : matrix)
for (int i = 0; i < rows.length; i++)
rows[i] = sc.nextInt( );
displayMatrix("\nMatrix Before - ");
for (int[ ] rows : matrix)
for (int i = 0; i < rows.length; i++)
rows[i] = reverse(rows[i]);
displayMatrix("\nMatrix After - ");
}
}