Formatting output of integers in to a table

My output prints:(after I feed it integers from a "Test" class array)
4 6 3 8 21
9 1 5 3 18
13 7 8 11 39
numbers are right, but I need to format the table
the output needs to look like this:
int int int int | rowsum
int int int int | rowsum
int int int int | rowsum
colsum colsum colsum colsum | total
How do I do this?
I have no idea?
I'm supposed to write a toString( ) method to format the table as nicely as possible, without
using the exotic formatting in the IO library.
This is what I have so far:
import java.awt.Graphics;
import java.applet.Applet;
public class TwoWayTable extends Applet {
int numRows;
int numCols;
int [] [] cell;
int [] rowSum;
int [] colSum;
int grandTotal;
public TwoWayTable(int [][] data){
cell = new int [data.length][data.length];
for(int i = 0; i < data.length; i++){
for(int j = 0; j < data.length; j++){
cell[i][j] = data[i][j];
calcTotals(cell);
for(int i = 0; i < cell.length; ++i){
for(int j = 0; j < cell.length; ++j){
System.out.print(cell[i][j] + " ");
System.out.println(rowSum + " ");
for(int j = 0; j < cell.length-1; ++j){
System.out.print(colSum[j] + " ");
System.out.println(colSum[cell.length-1] + " " + (grandTotal));
public void calcTotals(int [][] data2){
grandTotal = 0;
rowSum = new int[data2.length];
colSum = new int[data2.length];
for(int numRows = 0; numRows < data2.length; numRows++){
for(int numCols = 0; numCols < data2.length; numCols++){
grandTotal += data2[numRows][numCols];
rowSum[numRows] += data2[numRows][numCols];
colSum[numCols] += data2[numRows][numCols];
Would appreciate any help.

Try this code,
public class TwoWayTable
     int [][] cell;
     public static void main(String a[])
          int[][] data=new int[3][5];
          data[0]=new int[] {4,6,3,8,21};
          data[1]=new int[] {9,1,5,3,18};
          data[2]=new int[] {13,7,8,11,39};
          TwoWayTable tt=new TwoWayTable(data);
          System.out.println(tt.toString());
     public TwoWayTable(int data[][])
          cell = new int[data.length][data[0].length];
          cell = data;
     public String toString()
          StringBuffer sb = new StringBuffer("");
          for(int row=0;row<cell.length;row++)
               for(int col=0;col<cell[row].length;col++)
                    sb.append(cell[row][col]+"\t");
               sb.append("|\t"+calRowSum(cell[row])+"\n");
          int[] colSum=calColSum(cell);
          for(int num=0;num<colSum.length;num++)
               sb.append(colSum[num]+"\t");
          sb.append("|\t"+calRowSum(colSum));
          return sb.toString();
     public int calRowSum(int[] data)
          int total=0;
          for(int num=0;num<data.length;num++) total+=data[num];
          return total;
     public int[] calColSum(int[][] data)
          int[] totals=new int[5];
          for(int row=0;row<data.length;row++)
          for(int col=0;col<data[row].length;col++) totals[col]+=data[row][col];
          return totals;
}Sudha

Similar Messages

  • Formatting output values

    How can I format output money values to display 2 decimal digits ?
    For examole, for table values 1.20, 2.00 DBMS output displays 1.2 and 2. I want to display all missing zeroes.
    Thanks

    Use a format mask.
    SQL> select to_char(1.2,'999.99') from dual;
    TO_CHAR
    1.20
    SQL> select to_char(2.0,'999.99') from dual;
    TO_CHAR
    2.00

  • Initial-page-number not working in RTF format output

    A report has a parameter for the page number to start with. In rtf template below code is present
    <?initial-page-number:xdoxslt:ifelse(P_FIRST_PAGE_NUM!=’’,number(P_FIRST_PAGE_NUM),1)?>
    The report page number starts with the value which we pass in p_first_page_num in PDF format but in rtf format output it always starts with 1.
    Is initial-page-number not supported in RTF format output ? If not then what is the alternative?

    the method u followed is fine as need a page number staring from a specify value which u input.
    @section is only for resetting page number to 1 for every group and for that pdf and ppt will be fine but only for rtf u need to use that ( pressing F9).
    u can use @section and initial page number combined but they give u same output as get now. rtf output wont support it will only reset 1 every time
    What ever u do rtf output wont support initial page number code ..........
    i mentioned that F9 work around to mention that it is the only work around u have upto now to control rtf output with regards to page number.
    Guru's correct me if i am wrong. wait for a day or two if some one from guru's confirm it .
    If u need real confirmation raise an SR oracle will let u know .

  • 1.4.2 - What is the correct way to format output in the java.io.PrintStream

    With Java 1.4.2:
    What is the correct way to format output in the java.io.PrintStream?
    The following is incorrect, even though it is still used in the The JavaTM Tutorial at: http://java.sun.com/docs/books/tutorial/essential/
    System.out.formatThis returns "cannot resolve the method 'format'"
    Any detailed suggestions or information is greatly appreciated.

    The following is incorrect, even though it is still
    used in the The JavaTM Tutorial at:
    http://java.sun.com/docs/books/tutorial/essential/
    The whole format thing has been introduced in 1.5. The tutorial also states it's been "updated to 1.5.".
    That's all I've got to say for I don't know how you can format a PrintWriter, let alone a PrintStream, prior to 1.5. I'm not really sure there is any way. Any "legacy way", that is. There almost certainly are third-party API which achieve similar results.

  • List format output to excel sheet

    Hi,
        I have a report output in list format. I need to download that into excel sheet. Is it possible to download a list format output to excel sheet or shall I need to convert that into grid format?
    Thanks Barnita.

    HI,
    Use Menu path
    List->Save/Send->File path

  • SQL Developer formatted output

    Hello,
    Could you please help me in getting the formatted output on Oracle sql developer tool, I am not able to find andy options to set
    I have copy paste the result from this tool to excel, I am getting plain text out put, I have more columns and readablity is not there
    Regards,
    Neil
    Edited by: NeilCSE on Apr 6, 2010 6:01 AM

    Hi,
    try this.
    I am on windows
    SQL> spool c:\emp_text.txt;
    Started spooling to c:\emp_text.txt
    SQL> select ename||'|'||empno from emp;
    ENAME||'|'||EMPNO
    JAMES|7900
    FORD|7902
    MILLER|7934
    SMITH|7369
    ALLEN|7499
    WARD|7521
    JONES|7566
    MARTIN|7654
    BLAKE|7698
    CLARK|7782
    SCOTT|7788
    KING|7839
    TURNER|7844
    ADAMS|7876
    14 rows selected
    SQL> spool off;
    Stopped spooling to c:\emp_text.txtThen open in excel as delimeted by |
    Regards,
    Bhushan

  • How to get XML format output from Hyperion Financial Reporting

    Dears,
    We are using Hyperion Financial Reporting to replace FSG in fusion. I found that Hyperion FR report can be exported to html/excel/pdf format. However, I would like the report to export to xml format.It means I only need the xml data source.
    Anyone who knows how to get the xml format output from Hyperion FR, is there any avaiable API?

    I think if you export the report, you will be able to open the .des file in Notepad/Wordpad and see xml content.

  • Properly formatting output to XML

    While the code below would work to format something simple like this:
    <USERS>
    ��<USER>Tim Smith</USER>
    ��<USER>Jack Dempsey</USER>
    ��<USER>John Doe</USER>
    </USERS>
    hd.startDocument();
    AttributesImpl atts = new AttributesImpl();
    // USERS tag.
    hd.startElement("","","USERS",atts);
    for (int i=0;i<id.length;i++)
      atts.clear();
      hd.startElement("","","USER",atts);
      hd.characters(desc.toCharArray(),0,desc[i].length());
    hd.endElement("","","USER");
    hd.endElement("","","USERS");
    hd.endDocument();
    How does one do more complex nesting of xml elements? Such as if I wanted the output to resemble:
    <USERS>
    ��<USER>Tim Smith</USER>
    ��<ADDRESS>14 Main St</ADDRESS>
    ��<CITY>Denver</CITY>
    ��<STATE>CO</STATE>
    </USERS>
    Message was edited by:
    drakester
    Message was edited by:
    drakester

    I don't quit understand your answer. Serializing objects pertains to formatting output?

  • I am not able to open the html format outputs of SQR

    when I am trying to open SQR html formate output generated by SQR jobs not able to open the html format outputs of SQR getting below error
    but I am able to open pdf and excel formats outputs
    "An error was encountered while attempting to retrieve audit_control_info_frm.htm from the Hyperion Reporting and Analysis - System 9. This error is normally encountered when there is no free disk space on the machine hosting Hyperion Reporting and Analysis - System 9 Application. Hyperion Reporting and Analysis - System 9 Application uses a directory on the hard disk to store temporary files while downloading objects. To rectify this problem, if the disk hosting the Hyperion Reporting and Analysis - System 9 Application temporary directory is nearly full, free up additional disk space. After confirming that there is available disk space, restart ALL Hyperion Reporting and Analysis - System 9 servers. <p>Another possible cause of this error is that you have attempted to embed a "Versioned Collection" into your Personal Page. A "Versioned Collection" is typically created when you publish a document and request the creation of an additional compressed copy. Embedded "Versioned Collections" are not supported by Hyperion Reporting and Analysis - System 9.
    A general error was encountered contacting the server.
    Recommended Action: Contact your corporate technical support."

    Welcome to the Apple community.
    Have you tried restarting your web browser, if that doesn't help you might try emptying your web browser's cache.

  • HTML formatted output

    Hi All,
    I have xml source as,
    < SAMPLE_JOB>
    < ORG_DESCRIPTION>>& lt;UL& gt;& lt;LI& gt;& lt;DIV class=MsoNormal style=& quot;MARGIN: 0in 0in 0pt 0.25in& quot;
    & gt;& lt;SPAN style=& quot;FONT-SIZE: 10pt; COLOR: black; FONT-FAMILY: Arial; mso-bidi-font-size: 12.0pt& quot;
    & gt;Design and deliver technical training courses to field service engineers, dealer, and customer support
    personnel.& lt;/SPAN& gt;& lt;/DIV& gt;& lt;/LI& gt;& lt;/UL& gt;
    < /ORG_DESCRIPTION>
    < /SAMPLE_JOB>
    when i am previewing in pdf output, i am getting the following for < ORG_DESCRIPTION>
    < UL>< LI>< DIV class=MsoNormal style="MARGIN: 0in 0in 0pt 0.25in">< SPAN style="FONT-SIZE: 10pt; COLOR: black; FONT-FAMILY: Arial;
    mso-bidi-font-size: 12.0pt">Design and deliver technical training courses to field service engineers, dealer, and customer support personnel.< /SPAN>< /DIV>< /
    LI>< /UL>
    I want html formatted output. I saw tims blog. But here in my xml source i am not getting direct tags (instead of "< UL>", i am getting xml output as "& lt; UL & gt;"),
    can i also get the xsl equivalent code for tags like UL, LI, DIV, SPAN..
    Please help me.

    Your XML source is sorta odd.
    Where is it coming from?
    Word?
    This is what your xml should look like:
    < SAMPLE_JOB>
    < ORG_DESCRIPTION>Design and deliver technical training courses to field service engineers, dealer, and customer support
    personnel.< /ORG_DESCRIPTION>
    < /SAMPLE_JOB>
    Then you put it in your rtf and preview in pdf and it would look ok.
    The source xml is the problem - all this stuff is wrong or does not belong:
    & lt;/SPAN& gt;& lt;/DIV& gt;& lt;/LI& gt;& lt;/UL& gt;

  • Formatting output to a file? 1.4.2

    I am writing an application that writes result sets from an oracle 10g database query. This output combines both text and numeric.
    I cannot figure out how to justify the output to the right or left or force the fields to use a set amount of space regardless of the width of the text.
    As a result I get an outfile with perfectly lined up columns except for the one or two where instead of a four digit number there is a single number. This change in width shifts all of the output over.
    My customer goes nuts over this, surely there is a way to format output?

    OK, I tried today, I really did, I just can't get my brain around how to do what I need to accomplish so here is a pseudo example and i am hoping someone can shed some light.
    My application is abstract to enable easy addition of instances of automated reports.
    I have a 2d array that contains the column names for a given query. [0] = column name, [1] = space to be applied after results are added to a string buffer.
    So, something like this:
    StringBuffer entireQueryResults = new StringBuffer();
    String[][] QueryColumns = someObject.getQueryColumnNames();
    ResultSet currResults = someObject.getResultset();
    while(currResults.next()){
    String currRow = "";
    for(int i = 0; i < QueryColumns.length; i++){
       currRow = currRow + currResults.getString(QueryColumns[0])+currResults.getString(QueryColumns[i][1])+"\n";
    entireQueryResults.append(currRow);
    Now, the problem is that there are columns in the queries that have digits, these can range from a single val to 5 and while 98% of them are 3 digits there are random instances where they are a single digit or even a -1. When this happens it throws the output way off and makes it difficult to read in the resulting email report.
    How can I incorporate this into a MessageFormat or ChoiceFormat object to make the output pretty ?

  • Formatted output with JAXB

    Hi, Please help me with the formatting of output XML file using JAXB. This is my client program that marshals xml content into xml file. This program is creating XML file with no indentation at all. I commented out the line
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    still getting same xml file with no indentation. Am I doing anything wrong?
    Thanks in advance.
    try {
    // create a Validator
    Validator v = jc.createValidator();
    // validate the content tree
    boolean valid = v.validate( root );
    //logger.info("XML File Validated Successfully" );
         Marshaller m = jc.createMarshaller();
    m.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "http://mydomain.com/Schemas/data DT.xsd");
    DataWriter writer = new DataWriter(
    new OutputStreamWriter(new FileOutputStream(fileName),"UTF-8"),
    "UTF-8" );
    m.setProperty("com.sun.xml.bind.namespacePrefixMapper",new NamespacePrefixMapperImpl());
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    m.marshal(root, writer);
    }catch( ValidationException ue ) {
    logger.error( "Caught ValidationException"+ue ); throw new SdarsDBException("Validation Exception "+ue);
    } catch( JAXBException je ) {
    je.printStackTrace();
    } catch( IOException ioe ) {
    ioe.printStackTrace();

    Hi,
    try writing to the FileOutputStream directly.
    I get formatted output this way.
    maybe the DataWriter is doinfg some translatiopn for you?
    Chris

  • Can we change the default file format 'BIN' of system to 'ASC' using table

    can we change the default file format u2018BINu2019 of system to u2018ASCu2019 using table TSOPE
    if possible:will it affect any system performance

    Hello Vincent,
    BIN(Binary) is default selection.and so we have to select ascii.to make myself more clear my queries is like:
    first for setting ascii what we need to enter in text box that is against ASCII.and
    secondly if we select ASCII will it affect system performance in anyways.

  • Captivate MP4 format output

    Hi,
    I have generated the *.mp4 format output by using captivate 6.0. However, the output quality of the video is not satisfactory. The texts used in the demo are blurred and the image clarity is also not as expected.
    Can someone please help me out in generating a high quality video output.
    Thanks,
    Panendra

    OK.  Well that rules out one of the main reasons people see degradation in output quality,..resizing the content.
    My only other suggestion is that you may need to play around with the publishing settings in Captivate to see if changing something there will improve the quality.

  • Email attachment for text file using ABAP with funny format output

    Hi All,
    I am developing an ABAP program to generate an email to an external email address by using Function Module FUNCTION 'SO_DOCUMENT_SEND_API1. There is an attachment included in this program. The attachment is generated by reading through a data file from an Application Server and place it in the internal table before attaching it to the function module.
    Currently when I download the data file through SO01, I found that the data file looks a bit funny as below. It seems that all the letters are separated with an additional space in between.
    Funny Output:
    A B C D  1 2 3  A B C
    Suppose Output:
    ABCD 123 ABC
    I am not too sure if there is any output format that I need to set in order to make it works?

    hi Sree Ram,
    Thanks for your quick reply. The following is my code. I am not too sure if your reply will help to change the format of my data file or attachment sent through email.
    Thanks.
      CALL FUNCTION 'SO_DOCUMENT_SEND_API1'
        EXPORTING
          document_data              = w_doc_data
          put_in_outbox              = 'X'
          sender_address             = ld_sender_add
          sender_address_type        = ld_sender_add_type
          commit_work                = 'X'
        IMPORTING
          sent_to_all                = w_sent_all
        TABLES
          packing_list               = t_packing_list
          contents_bin               = t_attachment
          contents_txt               = it_message
          receivers                  = t_receivers
        EXCEPTIONS
          too_many_receivers         = 1
          document_not_sent          = 2
          document_type_not_exist    = 3
          operation_no_authorization = 4
          parameter_error            = 5
          x_error                    = 6
          enqueue_error              = 7
          OTHERS                     = 8.

Maybe you are looking for

  • Can't get iCloud to work properly from new MBP.

    I recently bought a new MBP and gave my old one to my wife. I deleted the calendar and contact info from my old MBP since she didn't need it. Only I didn't realize that it would also delete all the information from my new MBP that I had initialized f

  • Mail activity keeps counting incoming emails

    I just upgraded  my system to Mavericks Every time I check the mail , Mail is showing incoming phantom emails in the activity window. The number is growing by 2 every time I check even if nothing is arriving When I quit Mail and launch it back, it go

  • How to catch value ?

    Hi Friends, In BSP is there any way, to catch the value, like in JSP with following line of code String str = request.getParameter("val"); And now the string str, contains the value of (val), I would like to know any machanism other then navigation->

  • 70462 practice question

    hi all,   i have doubt about following question.. You administer a Microsoft SQL Server 2012 database that has Trustworthy set to On. You create a stored procedure that returns database-level information from Dynamic Management Views. You grant User1

  • IPhone 6 reset itself after visiting web page

    When browsing the Internet, an annoying pop up came up which I clicked on by accident. It was of adult nature and after about 3 seconds of that page loading, my phone turned itself off. Should I be concerned about this? Phone seems to be fine, I just