Beruflich Dokumente
Kultur Dokumente
Write down a java program to accept ‘N’ words and print all the words as per user’s choice:
1. Original order of input
2. Reverse order of input
3. Ascending order of input
4. Descending order of input
Use function Order() to arrange the data. Use function Display() to display the data. Use function InPuT() to take input.
Algorithm:
Step 1: Start
Step 2:
Program:
import java.io.*;
public class word
{
void inPut(String X[]) throws IOException
{
InputStreamReader read = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader (read);
int LN=X.length;
for(int i=0; i<LN;i++)
{
System.out.println("Enter a word");
X[i]=in.readLine();
X[i]=X[i].trim() + " ";
X[i]=(X[i].substring(0,(X[i].indexOf(' '))));//extract the first word
}
}
void Order(String X[], int ch)// function
{
int LN=X.length; //length of word
String temp=" "; //temporary String for swapping
switch(ch)
{
case 1: //empty case as the input and output are in same order
break;
case 2:
for (int i=0; i<LN/2;i++)
{
temp = X[i];
X[i]=X[LN-1-i];
X[LN-1-i]=temp;
}
break;
case 3:
int j;
for( int i=0;i<(LN-1);i++)
{
for (j=0;j<(LN-1-i);j++)
{
if(X[j].compareTo(X[j+1])>0)//arrange data in ascending order of alphabet
{
temp=X[j];
X[j]=X[j+1];
X[j+1]=temp;
}
}
}
break;
case 4:
for(int i=0;i<(LN-1);i++)
{
for(j=0; j<(LN-1-i);j++)
{
if(X[j].compareTo(X[j+1])<0) //arrange data in descending order of alphabet
{
temp = X[j];
X[j]=X[j+1];
X[j+1]=temp;
}
}
}
break;
default:
System.out.println("INVALID INPUT!!");
break;
}
}
void Display(String X[])
{
int LN=X.length;
for(int i=0;i<LN;i++)
{
System.out.print(X[i]+ " "); //to display
}
}
public static void main() throws IOException
{
InputStreamReader read = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader (read);
System.out.println("Enter the number of words to store in array");
int N=Integer.parseInt(in.readLine());
String a[]=new String[N];
System.out.println("Choose the following");
System.out.println(" 1. Display words in original order as entered");
System.out.println(" 2. Display words in reverse order of input");
System.out.println(" 3. Display words in ascending order of input");
System.out.println(" 4. Display words in descending order of input");
int chc= Integer.parseInt(in.readLine());
word ob=new word();
ob.inPut(a);
ob.Order(a,chc);
ob.Display(a);
}
}
Variable Description:
Output:
1) Enter the number of words to store in array
6
Choose the following
1. Display words in original order as entered
2. Display words in reverse order of input
3. Display words in ascending order of input
4. Display words in descending order of input
3
Enter a word
Happy
Enter a word
Sad
Enter a word
Angry
Enter a word
Crying out loud
Enter a word
Funny
Enter a word
Cranky
Angry Cranky Crying Funny Happy Sad