//Program to print the potential of each word in a sentence
import java.util.*;
public class WordPotential {
String sentence;
String[] words;
int[] potentials;
public WordPotential(String sent){
sentence = sent;
char last = sentence.charAt(sentence.length()-1);
if( last != '.' && last != '?' && last != '!')
System.out.println("INVALID INPUT");
else{
sentence=sentence.substring(0,sentence.length()-1);
words = sentence.split(" ");
potentials = new int[words.length];
for(int i=0; i<words.length; i++)
potentials[i] = calculatePotential(words[i]);
}
}
public static void main(String[] args){
Scanner s = new Scanner(System.in);
do{
run();
System.out.print("\nTo continue press 0: ");
} while(s.next().charAt(0) == '0');
}
public static void run(){
Scanner sc = new Scanner(System.in);
System.out.print("Enter sentence: ");
WordPotential obj = new WordPotential(sc.nextLine());
if(obj.words != null)
obj.display();
}
public int calculatePotential(String str){
int pot=0;
for(int i=0; i<str.length(); i++)
pot+= (int) str.charAt(i);
return pot;
}
public void display(){
for(int i=0; i<words.length; i++)
System.out.println(words[i] +" = "+ potentials[i]);
sort();
for(int i=0; i<words.length; i++)
System.out.print(words[i] + " ");
System.out.println();
}
public void sort(){
String temp;
int tempy;
for(int i=0; i<words.length-1; i++){
for(int j=0; j<words.length-i-1; j++){
if(potentials[j]> potentials[j+1]){
temp = words[j];
tempy = potentials[j];
words[j] = words[j+1];
potentials[j] = potentials[j+1];
words[j+1] = temp;
potentials[j+1] = tempy;
}
}
}
}
}
OUTPUT
Enter sentence: HELLO HOW ARE YOU DOING?
HELLO = 372
HOW = 238
ARE = 216
YOU = 253
DOING = 369
ARE HOW YOU DOING HELLO
To continue press 0: 1