Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package JavaApplication6;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.util.Arrays;
- public class JavaApplication6 {
- int [] arr = new int[10]; //initialize the container
- int item; //variable that will contain the inserted value
- void insertItem(int item, int index){
- if(index != arr.length){
- arr[index] = item;
- } else{
- System.out.println("Container is full!");
- }
- }
- void deleteItem(int index){
- if(index < 0){
- System.out.println("Item not found!");
- } else{
- arr[index] = 0;
- }
- }
- int findLocationInsert(){
- for(int i = 0; i < arr.length; i++){
- if(arr[i] == 0){
- return i;
- }
- }
- return arr.length;
- }
- /* Using linear search, if the inserted item match with array, the index containing the item
- * is returned. Otherwise, -1 is returned if the array does not contain the item.
- */
- int findLocationDelete(){
- for(int i = 0; i < arr.length; i++){
- if(arr[i] == item){
- return i;
- }
- }
- return -1;
- }
- void traverse(int [] arr){
- Arrays.sort(arr); //Using QuickSort, sort the elements first before accessing the array
- char punc; //punctuation mark
- //loop for accessing array
- for(int i = 0; i < arr.length; i++){
- //condition set for punc
- if(arr[i] != 0){
- if(i == arr.length - 1){
- punc = '.';
- } else{
- punc =',';
- }
- //print all elements of the container using text formatter
- System.out.printf(" %d%c",arr[i], punc);
- }
- }
- }
- public static void main(String[] args) throws IOException{
- JavaApplication6 array = new JavaApplication6();
- BufferedReader buff = new BufferedReader(new InputStreamReader(System.in));
- int option;
- //Simple UI
- do{
- System.out.print("\n1. Insert a value\n"
- +"2. Delete a value\n"
- +"3. Traverse\n"
- +"4. Exit\n"
- + "Selection: ");
- option = Integer.parseInt(buff.readLine());
- switch(option){
- case 1:
- System.out.print("Insert value: ");
- array.item = Integer.parseInt(buff.readLine());
- array.insertItem(array.item, array.findLocationInsert());
- break;
- case 2:
- System.out.print("Delete value: ");
- array.item = Integer.parseInt(buff.readLine());
- array.deleteItem(array.findLocationDelete());
- break;
- case 3:
- System.out.print("Elements: ");
- array.traverse(array.arr);
- System.out.println();
- break;
- default:
- option = 4; //exit by default
- }
- } while(option != 4);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement