Write a class with name ArrayDemo . This class has an array which should be initialized by user as given below. write a function with name display in this class.Call this display function in main function. [4 marks]
-1 4 1 6 3 8 5 10 7 12
import java.util.Scanner;
public class Q187266 {
public static class ArrayDemo {
private int integerArray[];
private int counter=0;
/**
* Constructor
* @param size
*/
public ArrayDemo(int size) {
this.integerArray=new int[size];
}
/**
* Adds a new value
* @param value
*/
public void addValue(int value) {
this.integerArray[counter]=value;
this.counter++;
}
/**
* Displays array
*/
public void display() {
for(int i=0;i<this.counter;i++) {
System.out.print(this.integerArray[i]+" ");
}
}
}
/**
* The start point of the program
*
* @param args
*/
public static void main(String[] args) {
ArrayDemo arrayDemo;
// Create Scanner object
Scanner keyboard = new Scanner(System.in);
try {
// Get the size of array
System.out.print("Enter a size of the array: ");
int size=keyboard.nextInt();
arrayDemo=new ArrayDemo(size);
for(int i=0;i<size;i++) {
System.out.print("Enter integer value: ");
int value=keyboard.nextInt();
arrayDemo.addValue(value);
}
arrayDemo.display();
} catch (Exception e) {
// Display error message
System.out.println(e.getMessage());
}
// close Scanner
keyboard.close();
}
}
Comments
Leave a comment