Ask Question
15 April, 13:59

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.

+3
Answers (1)
  1. 15 April, 17:51
    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?
Find 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 and Technology if you're in doubt about the correctness of the answers or there's no answer, then try to use the smart search and find answers to the similar questions.
Search for Other Answers