I am using PrintWriter to write the input from the standard input to a file, here I am trying to create an ascii table in the text file, but there is no proper alignment of the table in the text file. Here is my code guys.

package code.practise.MyIdeas;

import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;


public class WriteTextFile {
    public static void main(String[] args) throws FileNotFoundException {
        Scanner input = new Scanner(System.in);
        String name, email;
        final String EMAIL_PATTERN = 
                "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
                + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

        PrintWriter printwriter = new PrintWriter("User Details.txt");
        printwriter.println("+-----\t+-----\t+-----\t+");
        printwriter.println("|sno\t|Name\t|email\t|");
        printwriter.println("+-----\t+-----\t+-----\t+");
        try {
            A:for(int i = 1;;i++){                          
                System.out.println("Please enter the name:");
                System.out.println("You can quit by pressing enter key...");
                name = input.nextLine();
                System.out.println("Please enter the email:");
                email = input.nextLine();
                if(!email.matches(EMAIL_PATTERN)){                  
                    System.out.println("Please enter a valid email.\nThe details are not saved please start from the beginning.");
                    i--;
                    continue;
                }
                else
                {
                    printwriter.println("|"+i+")\t|"+name+"\t|"+email+"\t|");
                    printwriter.println("+-----\t+-----\t+-----\t+");
                }               
                for(;;){                
                    if(i>=1){                   
                        System.out.println("Do you wish to continue ?(y/n)");
                        String quit = input.nextLine();     
                        if(quit.equalsIgnoreCase("n"))break A;
                        else if (quit.equalsIgnoreCase("y")){
                            continue A;

                        }
                        else
                        {
                            System.out.println("Please enter either 'y' or 'n'");
                            continue;
                        }

                    }                   
                }
            }


        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        finally {
            input.close();
            printwriter.close();
        }
    }
}

And I am also attaching the created text file.

Thanks
Varun Krishna. P

Attachments
+-----	+-----	+-----	+
|sno	|Name	|email	|
+-----	+-----	+-----	+
|1)	|admin	|admin@domain.com	|
+-----	+-----	+-----	+
|2)	|dev1	|dev1@domain.com	|
+-----	+-----	+-----	+
|3)	|dev2	|dev2@domain.com	|
+-----	+-----	+-----	+
|4)	|tester	|tester@domain.com	|
+-----	+-----	+-----	+
|5)	|QA	|qa@domain.com	|
+-----	+-----	+-----	+
|6)	|Project Manager	|pm@domain.com	|
+-----	+-----	+-----	+

James Cherrill
I don't want it to show (format the string ) up in the console, I just want to format the output that appears in the text file.

Guys I am almost there, now I could not align the name and the email address. Here is my code

...
PrintWriter printwriter = new PrintWriter("User Details.txt");
printwriter.println("+---------+--------+---------+");
printwriter.printf("%-15s","|S.no     |Name    |Email    |\r\n");
printwriter.println("+---------+--------+---------+");
...
else
    {
        printwriter.printf("%-15s","|"+i+"        |"+name+"    |"+email+"     |\r\n");
        printwriter.printf("+---------+--------+---------+\r\n");                   
    }
...

And here is my text file, but the name and the email is not getting aligned properly.

Attachments
+---------+--------+---------+
|S.no     |Name    |Email    |
+---------+--------+---------+
|1        |admin    |admin@asdf.com     |
+---------+--------+---------+
|2        |dev    |dev@asdf.com     |
+---------+--------+---------+
|3        |project manager    |pm@asdf.com     |
+---------+--------+---------+

That's heading ih the right direction, so here's your next hint!
In the first argument you put all the fixed text, and format instructions for all the variable parts. The remining parameters are then the values for the variable parts. eg - I want a table with vertical bars, and the first col right justified 8 wide, and the second col 10 wide left aligned. My format spec looks like

"|%8s|%-10s|\n"

try running a couple of examples...

System.out.printf("|%8s|%-10s|\n","I","love");
System.out.printf("|%8s|%-10s|\n","Dani","Web");

Thanks James
Your message was very helpful for me to learn things, good explanation keep it up. Here is my final completed code.

package code.practise.MyIdeas;

import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;

public class WriteTextFile {
    public static void main(String[] args) throws FileNotFoundException {
        Scanner input = new Scanner(System.in);
        String name, email;
        final String EMAIL_PATTERN = 
                "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
                + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

        PrintWriter printwriter = new PrintWriter("User Details.txt");
        printwriter.println("+-----+--------------------+--------------------+");
        printwriter.printf("|%-5s|%-20s|%-20s|\r\n","S.no","Name","Email");
        printwriter.printf("+-----+--------------------+--------------------+\r\n");
        try {
            A:for(int i = 1;;i++){                  
                System.out.println("Please enter the name:");
//              System.out.println("You can quit by pressing enter key...");
                name = input.nextLine();
                System.out.println("Please enter the email:");
                email = input.nextLine();
                if(!email.matches(EMAIL_PATTERN)){                  
                    System.out.println("Please enter a valid email.\nThe details are not saved please start from the beginning.");
                    i--;
//                  break;
                    continue;
                }
                else
                {
                    printwriter.printf("|%5s|%20s|%20s|\r\n",i,name,email);
                    printwriter.printf("+-----+--------------------+--------------------+\r\n");                    
                }


                for(;;){                
                    if(i>=1){                   
                        System.out.println("Do you wish to continue ?(y/n)");
                        String quit = input.nextLine();     
                        if(quit.equalsIgnoreCase("n"))break A;
                        else if (quit.equalsIgnoreCase("y")){
                            continue A;

                        }
                        else
                        {
                            System.out.println("Please enter either 'y' or 'n'");
                            continue;
                        }

                    }                   
                }
            }


        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        finally {
            input.close();
            printwriter.close();
        }
    }

}

And here is my formatted text file.
Thanks
Varun Krishna. P

Attachments
+-----+--------------------+--------------------+
|S.no |Name                |Email               |
+-----+--------------------+--------------------+
|    1|               admin|      admin@asdf.com|
+-----+--------------------+--------------------+
|    2|          root admin|         ra@asdf.com|
+-----+--------------------+--------------------+
|    3|     project manager|         pm@asdf.com|
+-----+--------------------+--------------------+
|    4|   marketing manager|         mm@asdf.com|
+-----+--------------------+--------------------+
|    5|              Tester|     tester@asdf.com|
+-----+--------------------+--------------------+
|    6|                lead|       lead@asdf.com|
+-----+--------------------+--------------------+
|    7|                 dev|        dev@asdf.com|
+-----+--------------------+--------------------+

James and others
I have one more question though it is not related with alignment thing. I would like to track/detect the [esc] or [ctrl] + q key press in this console application. I am thinking to replace System.out.println("Do you wish to continue ?(y/n)"); with a code that could detect the [esc] or [ctrl]+ q key.

Sorry, I've literally never used the console in a real application, so I can't help.

One small suggestion: you have the same format string twice in the code (lines 17 and 34). That's the kind of thung that drives you mad when you (or someone else) are trying to change that code later. Much better to declare it once
static final String TABLE_FORMAT = "|%-5s|%-20s|%-20s|\r\n";
then use that for both the headings and the data, which will therefore always match.

Edited 2 Years Ago by JamesCherrill

James
I didn't notice the commonlity in line 17 and 34 good catch. I'll keep that in mind.

Edited 2 Years Ago by Varunkrishna: Typos

You are using Scanner class to accept an input (nextLine()), so you could simply test what the input would be. So what you may do is to convert the input String to bytes. If I remember correctly, the esc key gives you a byte array length of 1 with value of 27 inside. So you could check if the input value (after converted to byte array using getBytes() has size of 1 and the value inside is 27. Though, the user still has to press Enter key so the program will accept the value (for nextLine()). However, Ctrl+<any key> does not seem to be working for Java in the console...

Edited 2 Years Ago by Taywin

This question has already been answered. Start a new discussion instead.