1

I am trying to get a formatted output from 2 arrays one with the countries and the otyher with the populations which should provide an output as follows:

Egypt       |  92592000
France      |  66991000
Japan       | 126860000
Switzerland |   8401120

The only hint I received was that I should calculate the max width required for each column and then use that to align the values. This is what I have come up with so far but stuck on getting anything to output while formatting.

public static void main (String[] args) throws java.lang.Exception
{
    String [] countries = {"Egypt", "France", "Japan", "Switzerland"};
    int[] populations = {92592000, 66991000, 126860000, 8401120};
    printTable(countries, populations);
}

public static void printTable(String[] countries, int[] populations){
    int longestInput = 0;
    for(int i = 0; i < countries.length; i++){
        int countLength = countries[i].length();
        int popLength = String.valueOf(populations[i]).length();
        if(countLength + popLength > longestInput)
            longestInput = countLength + popLength;
    }

    for(int i = 0; i < countries.length; i++)
    System.out.format("%-10",countries[i] + " | " + populations[i]);
}
Andrew Tobilko
  • 44,067
  • 12
  • 74
  • 128
Nomadsoul
  • 15
  • 4
  • You need to calculate two maximum lengths: for countries, and for populations. Then you right pad each country with longestCountry and each population with longestPop, join those strings and print them. – Malte Hartwig Mar 21 '18 at 13:25
  • Why your main throws java.lang.Exception? – Maciej Pulikowski Mar 21 '18 at 13:25
  • its because of my attempt to format at the bottom if i remove that everything else works, or could be from the import java.util.*; import java.lang.*; import java.io.*; that i forgot to put into the snippet – Nomadsoul Mar 21 '18 at 13:26
  • Does that mean there are exceptions? I think you have to add a "conversion" to your format. Look at [this answer](https://stackoverflow.com/a/391978/7653073). – Malte Hartwig Mar 21 '18 at 13:30
  • that looks like it could help im going to give it a try now, I only get exception when I try to format the output cause if i don't it works fine – Nomadsoul Mar 21 '18 at 13:36

5 Answers5

2

Using Java 8

public static void main (String[] args) throws java.lang.Exception {
    String [] countries = {"Egypt", "France", "Japan", "Switzerland"};
    int[] populations = {92592000, 66991000, 126860000, 8401120};
    printTable(countries, populations);
}

public static void printTable(String[] countries, int[] populations) {
    if (countries.length == 0 || populations.length == 0 || countries.length != populations.length) {
        return;
    }
    int longestCountry = Arrays.stream(countries)
            .map(String::toString)
            .mapToInt(String::length)
            .max()
            .getAsInt();
    int longestPop = Arrays.stream(populations)
            .mapToObj(Integer::toString)
            .mapToInt(String::length)
            .max()
            .getAsInt();

    for (int i = 0; i < countries.length; i++) {
        System.out.printf("%-" + longestCountry + "s | %" + longestPop + "d%n", 
            countries[i], 
            populations[i]);
    }
}

The trick is using streams to get the lengths and using a negative format string to pad the right of the string.

jrtapsell
  • 5,698
  • 1
  • 21
  • 46
2

This is a little example how you can do it:

public static void main (String[] args) throws java.lang.Exception
  {
    String [] countries = {"Egypt", "France", "Japan", "Switzerland"};
    int[] populations = {92592000, 66991000, 126860000, 8401120};
    printTable(countries, populations);
  }

  public static void printTable(String[] countries, int[] populations){
    int countryLength = 0;
    long populationLength = 0;

    for(String country: countries){ //get longest country
      if (country.length() > countryLength)
        countryLength = country.length();
    }
    for(int i : populations) { //get longest number
      if(String.valueOf(i).length() > populationLength)
        populationLength = String.valueOf(i).length();
    }

    for(int i = 0; i < countries.length; i++) // print it out
      System.out.format("%-"+ (countryLength+1) +"s|%" + (populationLength+1) +"d\n",countries[i], populations[i]);
  }

First get the longest country:

for(String country: countries){ //get longest country
  if (country.length() > countryLength)
    countryLength = country.length();
}

Secondly get the longest population with String.valueOf(i).length():

for(int i : populations) { //get longest number
  if(String.valueOf(i).length() > populationLength)
    populationLength = String.valueOf(i).length();
}

Finally print it out with System.out.format:

System.out.format("%-"+ (countryLength+1) +"s|%" + (populationLength+1) +"d\n",countries[i], populations[i]);
Morchul
  • 1,697
  • 1
  • 4
  • 15
1

The pattern you are probably looking for is:

"%-" + maxCountryLength + "s | %" + maxPopulationLength + "d\n"
  • %-Xs means "X characters in width, a left-justified String"
  • %Xd means "X characters in width, a right-justified number"
  • \n means it occupies a line

The method might look like:

public static void printTable(String[] countries, int[] populations) {
    int defaultLength = 10;
    int maxCountryLength = stream(countries).mapToInt(String::length).max().orElse(defaultLength);
    int maxPopulationLength = stream(populations).mapToObj(Integer::toString).mapToInt(String::length).max().orElse(defaultLength);

    for (int i = 0; i < countries.length; i++) {
        System.out.format("%-" + maxCountryLength + "s | %" + maxPopulationLength + "d\n", countries[i], populations[i]);
    }
}

The result:

Egypt       |  92592000
France      |  66991000
Japan       | 126860000
Switzerland |   8401120
Andrew Tobilko
  • 44,067
  • 12
  • 74
  • 128
1

I rewrote the printTable method and it works perfectly:

public static void printTable(String[] countries, int[] populations)
{
    if(countries.length != 0)
    {

        int longestNameInput = countries[0].length();
        int longestPopInput = String.valueOf(populations[0]).length();

        for(int i = 0; i < countries.length; i++)
        {
            int countLength = countries[i].length();
            int popLength = String.valueOf(populations[i]).length();

            if(countLength > longestNameInput)
                longestNameInput = countLength;

            if(popLength > longestPopInput)
                longestPopInput = popLength;
        }

        for(int i = 0; i < countries.length; i++)
        {
            System.out.print(countries[i]);
            for(int j = 0; j < (longestNameInput - countries[i].length()); j++)
                System.out.print(" ");
            System.out.print(" | ");

            for(int k = 0; k < (longestPopInput - String.valueOf(populations[i]).length()); k++)
                System.out.print(" ");
            System.out.println(populations[i]);
        }

    }
}
Matt
  • 122
  • 1
  • 13
0
public static void main (String[] args) throws java.lang.Exception {
    String [] countries = {"Egypt", "France", "Japan", "Switzerland"};
    Integer[] populations = {92592000, 66991000, 126860000, 8401120};
    printTable(countries, populations);
}

public static void printTable(String[] countries, Integer[] populations){
    int longestInput = 0;
    for(int i = 0; i < countries.length; i++){
        int countLength = countries[i].length();
        int popLength = String.valueOf(populations[i]).length();
        if(countLength + popLength > longestInput)
            longestInput = countLength + popLength;
    }

    String longestString = getLongestString( countries );
    System.out.format("longest string: '%s'\n", longestString);

    Integer longestNumber = getLongestNumber( populations );
    System.out.format("longest Number: '%s'\n", longestNumber);

    for(int i = 0; i < countries.length; i++)
        System.out.format("%-" + longestString.length() + "s | %" + String.valueOf(longestNumber).length() + "d\n", countries[i], populations[i]);

}

To find the longest String in an array of Strings

public static String getLongestString(String[] array) {
    int maxLength = 0;
    String longestString = null;
    for (String s : array) {
        if (s.length() > maxLength) {
            maxLength = s.length();
            longestString = s;
        }
    }
    return longestString;
}

To find the longest Number in an array of Integers

public static Integer getLongestNumber(Integer[] array) {
    int maxLength = 0;
    Integer longestNumber = null;
    for (Integer i : array) {
        if (String.valueOf(i).length() > maxLength) {
            maxLength = String.valueOf(i).length();
            longestNumber = i;
        }
    }
    return longestNumber;
}

output «

longest string: 'Switzerland'
longest Number: '126860000'
Egypt       |  92592000
France      |  66991000
Japan       | 126860000
Switzerland |   8401120
Yash
  • 7,342
  • 2
  • 55
  • 63