Ask Question
26 August, 12:58

Write a method that accepts a string as an argument and returns a sorted string. For example, sort ("acb") returns abc. Write a test program that reads strings from a file and writes each sorted string to a different file.

+4
Answers (1)
  1. 26 August, 15:42
    0
    public static void sort (File nameOfFile) throws IOException {

    Scanner in = new Scanner (nameOfFile);

    File anotherFile = new File ("anotherFile. txt");

    anotherFile. createNewFile ();

    FileWriter fileWriter = new FileWriter (anotherFile);

    while (in. hasNextLine ()) {

    String word = in. nextLine (). toLowerCase ();

    String[] stringArray = word. split (" ");

    for (String s: stringArray) {

    char[] charArray = s. toCharArray ();

    Arrays. sort (charArray);

    String str = String. valueOf (charArray);

    fileWriter. write (str + " ");

    }

    fileWriter. write ("/n");

    }

    fileWriter. flush ();

    fileWriter. close ();

    }

    A complete program with a call to the the method sort is given in the explanation section

    Explanation:

    import java. io.*;

    import java. util. Arrays;

    import java. util. Scanner;

    public class StringSort{

    public static void main (String[] args) throws IOException{

    File nameOfFile = new File ("Myfile. txt");

    sort (nameOfFile);

    }

    public static void sort (File nameOfFile) throws IOException {

    Scanner in = new Scanner (nameOfFile);

    File anotherFile = new File ("anotherFile. txt");

    anotherFile. createNewFile ();

    FileWriter fileWriter = new FileWriter (anotherFile);

    while (in. hasNextLine ()) {

    String word = in. nextLine (). toLowerCase ();

    String[] stringArray = word. split (" ");

    for (String s: stringArray) {

    char[] charArray = s. toCharArray ();

    Arrays. sort (charArray);

    String str = String. valueOf (charArray);

    fileWriter. write (str + " ");

    }

    fileWriter. write ("/n");

    }

    fileWriter. flush ();

    fileWriter. close ();

    }

    }
Know the Answer?
Not Sure About the Answer?
Get an answer to your question ✅ “Write a method that accepts a string as an argument and returns a sorted string. For example, sort ("acb") returns abc. Write a test ...” in 📙 Computers & Technology if there is no answer or all answers are wrong, use a search bar and try to find the answer among similar questions.
Search for Other Answers