Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a program that performs the following tasks. (You can either use classical

ID: 3623233 • Letter: W

Question

Write a program that performs the following tasks.
(You can either use classical Vectors, or "generics" Vectors)

* The program should ask the user to input 10 String items, one at a time.
For each inputted data item, store it into a Vector.

* The program should then output all of the user's data items,
by using the Vector class's .toString() instance method.

* The program should then output all of the user's data items,
but without using the Vector class's .toString() method, and without
simply outputting the String variables that were used to receive the user's
original inputs.

Explanation / Answer

Vectors (the java.util.Vector class) are commonly used instead of arrays, because they expand automatically when new data is added to them. 

You can use a for loop to get all the elements from a Vector, but another very common way to go over all elements in a Vector is to use a ListIterator. 

The ListIterator uses the hasNext() method, which returns true if there are more elements, and next(), which returns the next element of the vector.

******************************************************************************

import java.util.Vector;

import java.util.Scanner;

import java.util.ListIterator;


public static void main(String[] args) {

Vector stringVector = new Vector();
Scanner in = new Scanner(System.in);

              System.out.println("Input 10 strings: ");

 

//The loop will iterate 10 times to acquire the inputs

                 for (int i = 0; i < 10; i++) {        

                          String string= in.next();        

                            stringVector.add(i, string);    

                              }

//prints the vector elements using the toString method
              System.out.println(stringVector.toString());


//prints the vector elements without using the toString method
              ListIterator iter = stringVector.listIterator();
                     while (iter.hasNext()) {
                             System.out.print((String) iter.next());
                      }

//prints the vector elements without using the toString method 

                    for (int i = 0; i < stringVector.capacity(); i++)

                                    System.out.print(" " + stringVector.elementAt(i)); 

                      }

          }

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote