Answer to Question #187266 in Java | JSP | JSF for Ali

Question #187266

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


1
Expert's answer
2021-04-29T23:53:26-0400


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();
	}


}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
APPROVED BY CLIENTS