Search This Blog

Tuesday, 30 December 2014

Java Program to Process a given String using String Object

0 comments
PROCESSING A STRING USING STRING OBJECT

AIM: To write a program in Java to get a name (string of characters) from the user and to find out the following:
    1. Length of the name
    2. Character ‘a’ is present or not in the name
    3. Location of ‘a’ present in the name

ALGORITHM:
  1. Declare an object of String named sName
  2. Declare variables of type int namely lCount, nIndex and fIndex for finding the length of the name, next index of ‘a’ and first index for searching the next occurance of ‘a’ in sName
  3. Get the name from the user and store it in sName using the object din of type DataInputStream
  4. Call the method length() of string object sName for finding the length and store it in lCount
  5. Call the method indexOf() of sName to find ‘a’ exists in it or not and store its result in nIndex
  6. Repeat the following until nIndex > 0 (i.e., next occurrence of ‘a’ exist)
    1. Print nIndex
    2. Set fIndex with the next value of nIndex (nIndex + 1)
    3. Call indexOf() on sName with the help of fIndex


PROGRAM:
import java.io.*;
public class StringObj
{
public static void main(String[] args) throws IOException
{
String sName;
int lCount, nIndex=0, fIndex;
DataInputStream din = new DataInputStream(System.in);
System.out.print("Enter a Name : ");
sName = din.readLine();
System.out.println("The given Name is : " + sName);
lCount = sName.length();
System.out.println("The length of the Name is : " + lCount);
nIndex = sName.indexOf('a');
if (nIndex > 0)
{
System.out.println("The letter a is Present in the Name");
System.out.println("The letter appears in the following Indexes :");
while (nIndex > 0)
{
System.out.println(nIndex + " ");
fIndex = nIndex + 1;
nIndex = sName.indexOf('a',fIndex);
}
}
}
}


Sample Run:

Leave a Reply