Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / First Aid / March 2005

Tip: Looking for answers? Try searching our database.

Text output alignment and format

Thread view: 
undbund - 09 Mar 2005 22:54 GMT
Hi, i have a program in C++ which i want to convert to Java.

#include <iostream>
#include <iomanip>
#include <math>
using namespace std;

int main()
{
    double amount, principle = 1000.00, rate = 0.05;

    cout << "Year" << setw(21) << "Amount on deposit" << endl;

    cout << setiosflags(ios::fixed | ios::showpoint | ios::right) <<
setprecision(2);

    for(int year = 1; year <= 10; year++)
    {
        amount = principle * pow(1.0 + rate, year);
        cout << setw(4) << year << setw(21) << amount << endl;
    }

    return 0;
}

/*
Output:

Year    Amount on deposit
  1              1050.00
  2              1102.50
  3              1157.63
  4              1215.51
  5              1276.28
  6              1340.10
  7              1407.10
  8              1477.46
  9              1551.33
 10              1628.89
*/

I just want to know if there are any functions similar to ios::right,
by which i can align the output of the data to right or left. In Java I
know that i can do this by adding together strings with characters like
"\t" or " " or using DecimalFormat. Is there any other way to achieve
the desired formatted output without using characters? Any code
examples or website address will much appreciated, especially examples
dealing with strings and using JDK 1.4.X

Thanks for all your help,
undbund
Anthony Borla - 10 Mar 2005 00:25 GMT
> Hi, i have a program in C++ which i want to convert to Java.
>
[quoted text clipped - 42 lines]
> ios::right, by which i can align the output of the data to
> right or left.

'ios::right', is a stream manipulator, basically a free-standing method [a
'function' in C++-speak] that filters stream data. Java's closest equivalent
are the FilterXXXStream classes. More information is available at:

   http://java.sun.com/docs/books/tutorial/essential/io/dataIO.html

You may find the DataInput / DataOutputStream examples instructive.

> In Java I know that i can do this by adding together strings
> with characters like "\t" or " " or using DecimalFormat. Is there
> any other way to achieve the desired formatted output without
> using characters? Any code examples or website address will
> much appreciated, especially examples dealing with strings and
> using JDK 1.4.X

Not sure if it will help, but below you will find some code which shows
several ways that string text may be aligned / padded. In all cases,
however, you are creating a new, appropriately-formatted, String object.
While this may not fully adress your requirements it may be a source of
ideas.

Also, you may consider using a package such as 'printf for Java', available
at:

   http://www.braju.com/

If you were using 1.5, a 'printf' facility is a standard offering.

I hope this helps.

Anthony Borla

// FILE: TestFieldAdjustment

import java.util.Arrays;

public class TestFieldAdjustment
{
 public static void main(String[] args)
 {
   if (args.length < 4)
     usage();

   int width = 0;

   try
   {
     width = Integer.parseInt(args[1]);
   }

   catch (NumberFormatException e)
   {
     usage();
   }

   String adjustedField;

   switch (args[3].charAt(0))
   {
     case 'L': adjustedField = padLeft(args[0], width,
                                                 args[2].charAt(0));
                  break;
     case 'C': adjustedField = centreField(args[0], width,
                                                 args[2].charAt(0));
                  break;
     case 'R': adjustedField = padRight(args[0], width,
                                                 args[2].charAt(0));
                  break;
     default: adjustedField = "UNADJUSTED";
   }

   System.out.println(adjustedField);
 }

 private static void usage()
 {
   System.err.println("Usage: java TestFieldAdjusment string"
                                + " width padchar L|C|R");
   System.exit(1);
 }

 private static String padLeft(String field, int fieldSize,
                         char padChar)
 {
   char[] padArray = new char[field.length() <= fieldSize
      ? fieldSize - field.length() : 0];

   Arrays.fill(padArray, padChar);

   return (new String(padArray)).concat(field);
   // Or: return String.copyValueOf(padArray).concat(field);
   // Or: return field.replaceFirst("$", new String(padArray));
 }

 private static String centreField(String field, int fieldSize,
                        char padChar)
 {
   int padLen = fieldSize - field.length();

   if (padLen < 1)
     return field;

   char[] fieldArray = new char[fieldSize];
   Arrays.fill(fieldArray, padChar);

   System.arraycopy(field.toCharArray(), 0, fieldArray,
                               (padLen / 2), field.length());

   return String.copyValueOf(fieldArray);
 }

 private static String padRight(String field, int fieldSize,
                              char padChar)
 {
   char[] padArray = new char[field.length() <= fieldSize
      ? fieldSize - field.length() : 0];

   Arrays.fill(padArray, padChar);

   return (new StringBuffer(field).append(padArray)).toString();
   // Or: return field.concat(String.copyValueOf(padArray));
   // Or: return field.replaceFirst("^", new String(padArray));
 }
}


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.