[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Java sort array alphabetically and print list

Posted on 2011-04-21
8
Medium Priority
?
852 Views
Last Modified: 2012-05-11
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
Comment
Question by:marchbaby
  • 6
8 Comments
 
LVL 47

Expert Comment

by:for_yan
ID: 35444227

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
 
LVL 47

Expert Comment

by:for_yan
ID: 35444236


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
 
LVL 47

Expert Comment

by:for_yan
ID: 35444263

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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 47

Expert Comment

by:for_yan
ID: 35444331

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
 
LVL 86

Expert Comment

by:CEHJ
ID: 35444338
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
 
LVL 47

Expert Comment

by:for_yan
ID: 35444374
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
 
LVL 47

Accepted Solution

by:
for_yan earned 2000 total points
ID: 35444723

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
 

Author Closing Comment

by:marchbaby
ID: 35448170
I understand now!! Thank you!
0

Featured Post

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
Suggested Courses
Course of the Month18 days, 14 hours left to enroll

834 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question