Monday, December 6, 2010

BASIC ARRAY of STRING

Let's say we will make a program that will get the name of every employee. Let's say we have 10 employees. To get every name of them, we will simply declare 10 String variable that will hold the inputted names of them. But what if, there's 20? are we going to declare 20 variables too? what if there's 50, a hundred or even a thousand or more? Using an array will lessen the variables that will be declared to hold every inputted data of the same type.
Any ways, in simple definition, Array holds multiple number of data of the same type within just one variable. Below, I will show you some basics on using of an array.

import java.util.Scanner;
public class UsingBasicArray
{
public static void main (String[] args)
{
String namesOfEmployees[] = new String[5];
//inside the square bracket is the array length. 
//I just made it 5 to make it short, 
//but you can make it even a hundred 
//or more depending on your necesity.
int ctr;
Scanner in = new Scanner(System.in);//Scanner is being instantiated here.
for(ctr=0;ctr<namesOfEmployees.length;ctr++)
{
System.out.print("Enter employee "+(ctr+1)+" name: ");
namesOfEmployees[ctr]=in.nextLine();
//right here, while the loop rotates
//you are actually locating where to put
//values in the array.
//ctr represents the index of where in you will
//put the inputted value.
}
for(ctr=0;ctr<namesOfEmployees.length;ctr++)
{
System.out.println("Employee "+(ctr+1)+" is "+namesOfEmployees[ctr]);
//right here is where you will call the values from
//every indices the inputted values are located.
//again, the ctr represents the index of the value
//that you are getting to display.
}
}
}

Here is a sample output of this source-code:


Enter employee 1 name: Marcelino Nyeto
Enter employee 2 name: Axle Dinozo
Enter employee 3 name: Mc Gyver
Enter employee 4 name: Allen Anatawa
Enter employee 5 name: Jhayvee Rozan

Employee 1 is Marcelino Nyeto
Employee 2 is Axle Dinozo
Employee 3 is Mc Gyver
Employee 4 is Allen Anatawa
Employee 5 is Jhayvee Rozan

From this you can experiment to make it broader. It's up to how your imagination can go... Good luck...

No comments:

Post a Comment