Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

1) First we need to compute an ordered form of each word. In this case, the orde

ID: 3768983 • Letter: 1

Question

1) First we need to compute an ordered form of each word. In this case, the ordered form of a word contains the same letters as the original, but in sorted order. So compose a static method

public static String orderedForm(String word)

so that orderedForm("computer") returns "cemoprtu", and orderedForm("poor") returns "oopr". For this first step, put this method in a little program OrderedWord.java that lets the user input one word and outputs its ordered form: java OrderedWord Enter word:

computer cemoprtu

To implement ordered Form, program a loop that reads the individual characters in the string parameter and puts them in an array of char or ArrayList. Thus orderedForm("poor") makes an array of 4 chars 'p', 'o', 'o', 'r' or an ArrayList with the corresponding Characters. Then sort that array or ArrayList. It will be easiest to use one of the JDK sort methods. For arrays you will want to use Arrays.sort(ca) (assuming that ca is your array of char), you will need to import java.util.Arrays if you use this. For ArrayLists you will want to use Collections.sort(cal) (assuming that cal is your ArrayList of Character), and you will need to import java.util.Collections if you use this. Finally, use the sorted characters to build a new String by a loop of s = s + c, where s is a String, and c is a char or Character. There is a much faster way of doing this without loops, but please use this way of doing it instead.

The program OrderedWord needs a main method as well as the orderedForm method. All it does is use a Scanner to get the word from the user and call orderedForm to convert it, and print out the resulting ordered form. Only do this once (get word from user, output ordered form of word) and then have the program end.

Explanation / Answer


import java.util.*;
import java.util.Arrays.*;
import java.util.Collections;
import java.util.Scanner;
public class ArrayListDemo {
   public static void main(String args[]) {
      // create an array list
       System.out.println("Enter a word ");
       Scanner scan=new Scanner(System.in);
       String str=scan.next();
      orderedForm(str);
    
   }
   public static void orderedForm(String str)
   {String newstr="";
   ArrayList al = new ArrayList();
  

      // add elements to the array list
      for(int i=0;i<str.length();i++)
      al.add(str.charAt(i));
      Collections.sort(al);
      System.out.println("Size of String: " + al.size());
for(int i=0;i<str.length();i++)
      newstr=newstr+al.get(i);
      // display the array list
      System.out.println("ordered form of word: " + newstr);
      // Remove elements from the array list
   }
}


output:

Enter a word
durga
Size of String: 5
ordered form of word: adgru