Search code examples
javaarraysstringsortingalphabetical

Any suggestions on how to change this class for reading Strings instead of doubles?


In classroom we made this class that sorts doubles and arranges them from min. to max. I'm interested in changing this class to read from a text file with names and sort them alphabetically instead of doubles that it reads from a numbers text file.

package versionDouble;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;

public class Datos {

    double[]  datos; 


    public Datos(String fileString) {

        int cuantos = contarDatos( fileString );

        this.datos = new double[ cuantos ];

        leerDatos( fileString );

    } // Datos


    private void leerDatos(String fileString) {

        try {

            Scanner scanner = new Scanner(new File(fileString));

            for (int i = 0; i < this.datos.length; i++) {

                this.datos[i] = scanner.nextDouble();

            } // for

            scanner.close();



        } catch (FileNotFoundException e) {

            e.printStackTrace();

        } // leerDatos


    } // Datos class 


    @Override
    public String toString() { 
        String string = "";

                string = Arrays.toString( this.datos ); 

        return string;

    } // toString


    private int contarDatos(String fileString) {


        int contador = 0;

        try {

            Scanner scanner = new Scanner( new File(fileString));

            while ( scanner.hasNext() ) {

                scanner.nextDouble();

                contador++;

            } // while

            scanner.close();

        } catch (FileNotFoundException e) {

            e.printStackTrace();

        } // catch

        return contador;

    } // contarDatos


    public void selectionSort() {


        for (int  startScan = 0;  startScan < this.datos.length;  startScan++) {

            int minIndex = startScan;

            double minValue = this.datos[ minIndex ]; 

            for (int index = 0; index < this.datos.length; index++) {

                if( this.datos[ index ] < minValue) {

                    minIndex = index;
                    minValue = this.datos[ index ];

                } // if

            } // for interno

            if(  minIndex != startScan  ) {

                double temporary = this.datos[startScan];

                this.datos[ startScan ] = this.datos[ minIndex ];

                this.datos [ minIndex ] = temporary;

            } // swap

        } // for externo

        Arrays.sort( this.datos );

    } // selectionSort

} //  Class

Solution

  • You will need to call a different member function on Scanner, for example next() or nextLine(). Also, change the data type of several variables to store strings instead of floating-point numbers. Also you will have to find a way to compare the string alphabetically instead of numerically.