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.

Respuesta :

ijeggs

Answer:

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();

   }

}