Lab 5

Description:

In this lab, the program first asks the user what data type will be used, and how many entries will be entered. Then, after the data is entered, the program will be displaying entered data in different data structure. The first is array list, the second is stack, the third is treemap, and the fourth is treeset.

Code:

package Lab5;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;
import java.util.Stack;
import java.util.TreeMap;
import java.util.TreeSet;

public class DataStructures {

	public static void main(String[] args) {

		Scanner userInput =  new Scanner(System.in);
		String dataType, arrayLength;
		Object[] dataStream = null ;

		System.out.println("Select what type of data will be entered:\n"
				+"1. String\n"
				+"2. Double\n" 
				+"3. Integer\n");
		dataType  =  userInput.nextLine();

		System.out.println("How many elements to process:");
		arrayLength = userInput.nextLine();

		try {
			Integer.parseInt(arrayLength);
		} catch (java.lang.NumberFormatException e) {
			System.out.println("Invalid Input");
			return;
		}

		switch(dataType) {
		case "1":
			dataStream = new String[Integer.parseInt(arrayLength)];
			break;
		case "2":
			//dataStream = new double[Integer.parseInt(arrayLength)];
			break;
		case "3":
			dataStream = new Integer[Integer.parseInt(arrayLength)];
			break;
		}

		for(int i = 0; i !=Integer.parseInt(arrayLength);i++){
			System.out.println("Enter data " + (i+1));
			dataStream [i] = userInput.nextLine();
		} 

		//1.
		ArrayList dataArrayList = new ArrayList(Arrays.asList(dataStream));

		System.out.println(dataArrayList);

		//2.
		Stack dataStack = new Stack();

		int j = 0; 
		do{
			dataStack.push(dataStream[j]);
			j++;
		}while(dataStack.size() != dataStream.length);

		do{
		System.out.print(dataStack.pop()+" ");
		} while (dataStack.size() != 0);

		//3.
		TreeMap dataTree = new TreeMap();

		j=0;
		do{
		dataTree.put(j,dataStream[j]);

		}while (j != dataStream.length);

		j=0;
		do{
		System.out.print(dataTree.get(j));
		}while (j != dataTree.size());

		//4.
		TreeSet dataSet = new TreeSet();

		j = 0; 
		do{
			try{dataSet.add(dataStream[j]);
			j++;
			}catch(ArrayIndexOutOfBoundsException e){
				break;
			}
		}while(dataSet.size() != dataStream.length);

		System.out.println("\n"+dataSet);

	}

}

Screenshot:

Capture

Leave a Reply

Your email address will not be published. Required fields are marked *