• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 881
  • Last Modified:

Java sort array alphabetically and print list

Hi,
First I am extremely grateful for the help I have received so far here. I have to sort and display the mortgage information with the sorting done alphabetically by last name. I know the phone number is written in a subclass, but I had to do that for the assignment. I have some stuff written, but I'm at a loss how to print all the array info starting with last name, then first name alphabetically.
import java.io.*;
import java.text.*;


public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

        String[] fname = new String[30];
        String[] lname = new String[30];
        double[] loanAmount = new double[30];
        double[] rateYears = new double[30];
        int[] termYears = new int[30];
        boolean yes = true;

        int count = 0;

        System.out.println("\t\t\tWelcome to yet another Mortgage Calculator\n");

        while (yes) {
            System.out.println("\tPlease enter your first name:");

            String fname1 = in.readLine();

            while (fname1.equals("")) {
                System.out.println(
                    "\tName error! Please enter your first name: ");
                fname1 = in.readLine();
            }

            fname[count] = fname1; //into the array it goes

            System.out.println("\tPlease enter your last name:");

            String lname1 = in.readLine();

            while (lname1.equals("")) {
                System.out.println(
                    "\tName error! Please enter your last name: ");
                lname1 = in.readLine();
            }

            lname[count] = lname1; //into the array

    //sort array

            java.util.Arrays.sort(lname, String.CASE_INSENSITIVE_ORDER);


            class phoneNum extends Main{
                String phoneNum;
            }

           System.out.println("Please enter your phone number with dashes"); //asking for phone number
            String phoneNum = in.readLine(); //getting user input
           
           
           

            System.out.print("\tPlease enter the loan Amount: $"); //asks for loan amount

            String input = in.readLine(); //user input

            double loanAmount1 = Double.parseDouble(input);

            while (loanAmount1 <= 0) {
                System.out.println(
                    "Invalid Number, please enter the loan Amount: ");
            }

            loanAmount[count] = loanAmount1; //into the array it goes

            System.out.print( //asks for interest rate
                "\tPlease enter the interest rate:  ");

            String inputa = in.readLine();
            double rateYears1 = Double.parseDouble(inputa);

            while (rateYears1 <= 0) {
                System.out.println(
                    "Invalid Number, please enter the interest rate: ");
            }

            rateYears[count] = rateYears1;

            System.out.print("\tPlease enter the length of mortgage years ");

            String inputb = in.readLine();

            int termYears1 = Integer.parseInt(inputb);

            termYears[count] = termYears1; //into the array it goes

            DecimalFormat precision2p = new DecimalFormat("$###,###.00");

            double rateMonthly = (rateYears1 / 12) / 100; // monthly calculation & interest rate
            double termMonths = (termYears1 * 12); // monthly calculation & interest rate

            //monthlyPayment calculation continued
            double monthlyPayment = (loanAmount1 * rateMonthly) / (1 -
                Math.pow(1 + rateMonthly, -termMonths));


            System.out.println("\tClient last name: \n" +lname);
            System.out.println("\tClient first name: \n" +fname);
            System.out.println("\tClient phone Number: \n" +phoneNum);

            System.out.println("\tThe mortgage payment will be: " +
                precision2p.format(monthlyPayment));

            {
                System.out.print(
                    "Would you want to enter another person? (y/n): ");

                String inputc = in.readLine();
                yes = inputc.equalsIgnoreCase("y");
            }
        }
    }
    }

Open in new window

0
marchbaby
Asked:
marchbaby
  • 6
1 Solution
 
for_yanCommented:

Thiis is how you can sort arry:

ArrayList al = new ArrayList();

for(int j=0; j<fnames.length; j++)al.sdd(fnames[j]);

Collections.sort(al);

for(int j=0; j<al.size(); j++)fnames[j] = (String) al.get(j);














0
 
for_yanCommented:


Spelling correction:

ArrayList al = new ArrayList();

for(int j=0; j<fnames.length; j++)al.add(fnames[j]);

Collections.sort(al);

for(int j=0; j<al.size(); j++)fnames[j] = (String) al.get(j);


0
 
for_yanCommented:

You can do it with all your arrays or you can make a method

public String [] getOrderedArray(String [] fnames){
ArrayList al = new ArrayList();

String fnames1 = new String[fnames.length];

for(int j=0; j<fnames.length; j++)al.add(fnames[j]);

Collections.sort(al);

for(int j=0; j<al.size(); j++)fnames1[j] = (String) al.get(j);

return fnames1;

}

after that you can write everywere in your code:

lnames = getOrderedArray(lnames);
fnames = getOrderedArray(fnames);
and arrays lnames, fnames become ordered


0
Cloud Class® Course: Microsoft Exchange Server

The MCTS: Microsoft Exchange Server 2010 certification validates your skills in supporting the maintenance and administration of the Exchange servers in an enterprise environment. Learn everything you need to know with this course.

 
for_yanCommented:

You can usee Array.sort,
but it should be moved to another location in you program (see below):

import java.io.*;
import java.text.*;
import java.util.Arrays;


public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

        String[] fname = new String[30];
        String[] lname = new String[30];
        double[] loanAmount = new double[30];
        double[] rateYears = new double[30];
        int[] termYears = new int[30];
        boolean yes = true;

        int count = 0;

        System.out.println("\t\t\tWelcome to yet another Mortgage Calculator\n");

        while (yes) {
            System.out.println("\tPlease enter your first name:");

            String fname1 = in.readLine();

            while (fname1.equals("")) {
                System.out.println(
                    "\tName error! Please enter your first name: ");
                fname1 = in.readLine();
            }

            fname[count] = fname1; //into the array it goes

            System.out.println("\tPlease enter your last name:");

            String lname1 = in.readLine();

            while (lname1.equals("")) {
                System.out.println(
                    "\tName error! Please enter your last name: ");
                lname1 = in.readLine();
            }

            lname[count] = lname1; //into the array

    //sort array

            //Arrays.sort(lname);

           for(int j=0; j<lname.length; j++) System.out.println(lname[j]);


            class phoneNum extends Main{
                String phoneNum;
            }

           System.out.println("Please enter your phone number with dashes"); //asking for phone number
            String phoneNum = in.readLine(); //getting user input




            System.out.print("\tPlease enter the loan Amount: $"); //asks for loan amount

            String input = in.readLine(); //user input

            double loanAmount1 = Double.parseDouble(input);

            while (loanAmount1 <= 0) {
                System.out.println(
                    "Invalid Number, please enter the loan Amount: ");
            }

            loanAmount[count] = loanAmount1; //into the array it goes

            System.out.print( //asks for interest rate
                "\tPlease enter the interest rate:  ");

            String inputa = in.readLine();
            double rateYears1 = Double.parseDouble(inputa);

            while (rateYears1 <= 0) {
                System.out.println(
                    "Invalid Number, please enter the interest rate: ");
            }

            rateYears[count] = rateYears1;

            System.out.print("\tPlease enter the length of mortgage years ");

            String inputb = in.readLine();

            int termYears1 = Integer.parseInt(inputb);

            termYears[count] = termYears1; //into the array it goes

            DecimalFormat precision2p = new DecimalFormat("$###,###.00");

            double rateMonthly = (rateYears1 / 12) / 100; // monthly calculation & interest rate
            double termMonths = (termYears1 * 12); // monthly calculation & interest rate

            //monthlyPayment calculation continued
            double monthlyPayment = (loanAmount1 * rateMonthly) / (1 -
                Math.pow(1 + rateMonthly, -termMonths));


            System.out.println("\tClient last name: \n" +lname);
            System.out.println("\tClient first name: \n" +fname);
            System.out.println("\tClient phone Number: \n" +phoneNum);

            System.out.println("\tThe mortgage payment will be: " +
                precision2p.format(monthlyPayment));

            {
                System.out.print(
                    "Would you want to enter another person? (y/n): ");

                String inputc = in.readLine();
                yes = inputc.equalsIgnoreCase("y");
            }
        }
         Arrays.sort(lname);
           for(int j=0; j<lname.length; j++) System.out.println(lname[j]);
    }
    }

Open in new window

0
 
CEHJCommented:
You will eventually run into trouble with your arrays - parallel arrays are difficult to maintain and won't scale well.

What you be much better is to have a Customer class containing the correct data, and then you can sort instances of Customer
0
 
for_yanCommented:
No actually the code which I posted how to order was correct.
You can also use Array.sort - also in general correct
Your code is incorrect and i diidn't correct it either,
requires some more corrections

In general parallel arrays are not good but at this stage you probably would
be OK with them - to sort instnaces of Customer will be next stage
0
 
for_yanCommented:

This is how it works.
You can add sorting and printing other arrays
at the bottom , not just last names
and also correct printing the phone
- you don't need any special
class for the phone   - just read it
into string


import java.io.*;
import java.text.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;


public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

        String[] fname = new String[30];
        String[] lname = new String[30];
        double[] loanAmount = new double[30];
        double[] rateYears = new double[30];
        int[] termYears = new int[30];
        boolean yes = true;

        int count = 0;

        System.out.println("\t\t\tWelcome to yet another Mortgage Calculator\n");

        while (true) {
            System.out.println("\tPlease enter your first name :");

            String fname1 = in.readLine();

            while (fname1.trim().equals("end")) {

                System.out.println("End");
                break;

            }


            fname[count] = fname1; //into the array it goes

            System.out.println("\tPlease enter your last name:");

            String lname1 = in.readLine();

            while (lname1.equals("")) {
                System.out.println(
                    "\tName error! try again from the beginning: ");
                continue;
            }

            lname[count] = lname1; //into the array

        //    }

           System.out.println("Please enter your phone number with dashes"); //asking for phone number
            String phoneNum = in.readLine(); //getting user input




            System.out.print("\tPlease enter the loan Amount: $"); //asks for loan amount

            String input = in.readLine(); //user input

            double loanAmount1 = Double.parseDouble(input);

            while (loanAmount1 <= 0) {
                System.out.println(
                    "Invalid Number, try again form the beginning: ");
                 continue;
            }

            loanAmount[count] = loanAmount1; //into the array it goes

            System.out.print( //asks for interest rate
                "\tPlease enter the interest rate:  ");

            String inputa = in.readLine();
            double rateYears1 = Double.parseDouble(inputa);

            while (rateYears1 <= 0) {
                System.out.println(
                    "Invalid Number,try again form the beginning: ");
                   continue;
            }

            rateYears[count] = rateYears1;

            System.out.print("\tPlease enter the length of mortgage years ");

            String inputb = in.readLine();

            int termYears1 = Integer.parseInt(inputb);

            termYears[count] = termYears1; //into the array it goes

            DecimalFormat precision2p = new DecimalFormat("$###,###.00");

            double rateMonthly = (rateYears1 / 12) / 100; // monthly calculation & interest rate
            double termMonths = (termYears1 * 12); // monthly calculation & interest rate

            //monthlyPayment calculation continued
            double monthlyPayment = (loanAmount1 * rateMonthly) / (1 -
                Math.pow(1 + rateMonthly, -termMonths));


            System.out.println("\tClient last name: \n" +lname);
            System.out.println("\tClient first name: \n" +fname);
            System.out.println("\tClient phone Number: \n" +phoneNum);

            System.out.println("\tThe mortgage payment will be: " +
                precision2p.format(monthlyPayment));


                System.out.print(
                    "Would you want to enter another person? (y/n): ");

                String inputc = in.readLine();

               count++;
               if(inputc.equalsIgnoreCase("y")) continue;
              else break;

        }

             Arrays.sort(lname,0, count);
         for(int j=0; j<count; j++) System.out.println(lname[j]);


    }

  


    }

Open in new window


Ouput:

"C:\Program Files\Java\jdk1.6.0_19\bin\java" -Didea.launcher.port=7548 "-Didea.launcher.bin.path=C:\Program Files\JetBrains\IntelliJ IDEA 9.0.1\bin" -Dfile.encoding=windows-1252 -classpath "C:\Program Files\Java\jdk1.6.0_19\jre\lib\alt-rt.jar;C:\Program Files\Java\jdk1.6.0_19\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.6.0_19\jre\lib\deploy.jar;C:\Program Files\Java\jdk1.6.0_19\jre\lib\javaws.jar;C:\Program Files\Java\jdk1.6.0_19\jre\lib\jce.jar;C:\Program Files\Java\jdk1.6.0_19\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.6.0_19\jre\lib\management-agent.jar;C:\Program Files\Java\jdk1.6.0_19\jre\lib\plugin.jar;C:\Program Files\Java\jdk1.6.0_19\jre\lib\resources.jar;C:\Program Files\Java\jdk1.6.0_19\jre\lib\rt.jar;C:\Program Files\Java\jdk1.6.0_19\jre\lib\ext\dnsns.jar;C:\Program Files\Java\jdk1.6.0_19\jre\lib\ext\localedata.jar;C:\Program Files\Java\jdk1.6.0_19\jre\lib\ext\sunjce_provider.jar;C:\Program Files\Java\jdk1.6.0_19\jre\lib\ext\sunmscapi.jar;C:\Program Files\Java\jdk1.6.0_19\jre\lib\ext\sunpkcs11.jar;C:\idea_9_temp_projects\ForEE1\out\production\ForEE1;C:\idea_9_temp_projects\ForEE1\lib\core-renderer-R8pre2.jar;C:\idea_9_temp_projects\ForEE1\lib\iText-5.0.6.jar;C:\Program Files\JetBrains\IntelliJ IDEA 9.0.1\lib\idea_rt.jar" com.intellij.rt.execution.application.AppMain Main
			Welcome to yet another Mortgage Calculator

	Please enter your first name :
alex
	Please enter your last name:
aaaaaa
Please enter your phone number with dashes
2342323
	Please enter the loan Amount: $1000
	Please enter the interest rate:  1
	Please enter the length of mortgage years 1
	Client last name: 
[Ljava.lang.String;@1fb8ee3
	Client first name: 
[Ljava.lang.String;@61de33
	Client phone Number: 
2342323
	The mortgage payment will be: $83.79
Would you want to enter another person? (y/n): y
	Please enter your first name :
pete
	Please enter your last name:
bbbbbb
Please enter your phone number with dashes
1234
	Please enter the loan Amount: $2000
	Please enter the interest rate:  2
	Please enter the length of mortgage years 2
	Client last name: 
[Ljava.lang.String;@1fb8ee3
	Client first name: 
[Ljava.lang.String;@61de33
	Client phone Number: 
1234
	The mortgage payment will be: $85.08
Would you want to enter another person? (y/n): n
aaaaaa
bbbbbb

Process finished with exit code 0

Open in new window

0
 
marchbabyAuthor Commented:
I understand now!! Thank you!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 6
Tackle projects and never again get stuck behind a technical roadblock.
Join Now