Java - Read and Print N names using Vector in Java.


IncludeHelp 11 September 2016

In this code snippet/example we will learn how to read and print N names (strings) using Vector in Java?

This is an example of Vector in Java, this example will read and print N strings (names) using Java Victor.

To print all vector elements, we are using Enumeration.

Java Code Snippet - Read and Print N Names using Vector in Java (Example of Vector)

//Java - Read and Print N names using Vector in Java

import java.util.*;
import java.util.Scanner;
 
class ExampleVector
{
	public static void main(String args[])
	{
		Vector names;
		names=new Vector();
		String text=null;
		int choice=0;
		
		Scanner SC=new Scanner(System.in);
		
		while(true){
			System.out.print("Enter name: ");
			text=SC.next();
			//add into vector
			names.add(text);
			
			System.out.print("More... (0 to exit): ");
			choice=SC.nextInt();
			if(choice==0)
				break;
		}
		
		//display all names
		Enumeration en=names.elements();
		
		System.out.println("All entered names are:");
		
		while(en.hasMoreElements()){
			System.out.println(en.nextElement());
		}				
	}
}
    

    Enter name: Mike
    More... (0 to exit): 1
    Enter name: Priya
    More... (0 to exit): 1
    Enter name: Alak
    More... (0 to exit): 0
    All entered names are:
    Mike
    Priya
    Alak




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.