The potential of a word is found by adding the ASCII value of the alphabets.
(ASCII values of A to Z are 65 to 90).
(ASCII values of A to Z are 65 to 90).
Example: BALL
Potential = 66 + 65 + 76 + 76 = 283
Write a program to accept a sentence which may be terminated by either “ . ” , “ ? ” or “ ! ” only.
The words of sentence are separated by single blank space and are in UPPER CASE. Decode the
words according to their potential and arrange them in ascending order of their potential strength.
Test your program with the following data and some random data:
Example 1:
INPUT: HOW DO YOU DO?
OUTPUT: HOW = 238
DO = 147
YOU = 253
DO = 147
DO DO HOW YOU
Example 2:
INPUT: LOOK BEFORE YOU LEAP.
OUTPUT: LOOK = 309
BEFORE = 435
YOU = 253
LEAP = 290
YOU LEAP LOOK BEFORE
Example 3:
INPUT: HOW ARE YOU#
OUTPUT: INVALID INPUT
import java.util.StringTokenizer;
class Potential
{
void main(String s)
{
int l=s.length();
int n;
int x=0;
int c=0;
String a[]=new String[100];
int arr[]=new int[100];
if(s.charAt(l-1)=='.'||s.charAt(l-1)==','||s.charAt(l-1)=='!'||s.charAt(l-1)=='?')
s=s.substring(0,l-1);
else
{
System.out.println("INVALID INPUT");
System.exit(0);
}
StringTokenizer stk=new StringTokenizer(s);
while(stk.hasMoreTokens())
{
String s1=stk.nextToken();
int f=ascii(s1);
a[c++]=s1;
arr[x++]=f;
}
for(int i=0;i<c;i++)
{
System.out.println("Token: "+a[i]+ " Potential: "+arr[i]);
}
sort(a,arr,c);
}
private int ascii(String s1)
{
int z=0;
int l=s1.length();
for(int i=0;i<l;i++)
{
int c=s1.charAt(i);
z=z+c;
}
return z;
}
private void sort(String a[],int arr[], int c)
{
for(int i=0;i<c;i++)
{
for(int j=0;j<c-i-1;j++)
{
if(arr[j]>arr[j+1])
{
int t=arr[j+1];
arr[j+1]=arr[j];
arr[j]=t;
String s=a[j+1];
a[j+1]=a[j];
a[j]=s;
}
}
}
for(int i=0;i<c;i++)
{
System.out.print(a[i]+" ");
}
}
public static void main(String args[])
{
Potential obj = new Potential ();
obj.main("This is a test?");
}
}
No comments:
Post a Comment