Ask Question
2 August, 22:40

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. 2 August, 23:04
    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 & Technology if the answers seem to be not correct or there’s no answer. Try a smart search to find answers to similar questions.
Search for Other Answers