Advertisement
Guest User

Untitled

a guest
Jan 21st, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.18 KB | None | 0 0
  1. public class PositionWordCombiner {
  2. private String original,words[];
  3. int charsCount;
  4.  
  5. public PositionWordCombiner(String word, String delimeter){
  6. setWords(word,delimeter);
  7. setCharCount();
  8. }
  9.  
  10. public String toString(){
  11. return getWordsCombined();
  12. }
  13.  
  14. public String getWordsCombined(){
  15. StringBuilder result = new StringBuilder("ORIGINAL MSG : ");
  16. result.append(getOriginalWord());
  17. result.append("\n");
  18. result.append("COMBINED WORDS : ");
  19. for(int ch = 0; ch < getCountOFChars(); ++ch)
  20. result.append(getCharsAt(ch));
  21. return result.toString();
  22. }
  23.  
  24. private String getCharsAt(int pos){
  25. StringBuilder result = new StringBuilder();
  26. for(String s : words)
  27. result.append(s.charAt(pos));
  28. return result.toString();
  29. }
  30.  
  31. private void setWords(String w,String d){
  32. original = w;
  33. words = w.split(d);
  34. }
  35.  
  36. /*
  37. * to avoid an IndexOutBoundException
  38. * we need to know the length of the
  39. * word considered to be smallest
  40. */
  41. private void setCharCount(){
  42. charsCount = getSmallestWord().length();
  43. }
  44.  
  45. public String getSmallestWord(){
  46. String smallest = words[0];
  47. for(int i = 1; i < getNumOfWords(); ++i)
  48. if(words[i].compareTo(smallest) < 0)
  49. smallest = words[i];
  50. return smallest;
  51. }
  52.  
  53. public String getOriginalWord(){
  54. return original;
  55. }
  56.  
  57. public int getCountOFChars(){
  58. return charsCount;
  59. }
  60.  
  61. public int getNumOfWords(){
  62. return words.length;
  63. }
  64. }
  65.  
  66. public class WordsCombinerDemo {
  67. public static void main(String[] args){
  68. PositionWordCombiner[] pwc = new PositionWordCombiner[3];
  69. for(int i = 0; i < pwc.length; ++i){
  70. String input = JOptionPane.showInputDialog("enter word" + (i + 1));
  71. pwc[i] = new PositionWordCombiner(input," ");
  72. }
  73. //display results
  74. for(int i = 0; i < pwc.length; ++i){
  75. System.out.printf("WORD # %d \n%s \n\n",i + 1,pwc[i]);
  76. }
  77. }
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement