Output in a table format in Java's System.out
Use System.out.format
. You can set lengths of fields like this:
System.out.format("%32s%10d%16s", string1, int1, string2);
This pads string1
, int1
, and string2
to 32, 10, and 16 characters, respectively.
See the Javadocs for java.util.Formatter
for more information on the syntax (System.out.format
uses a Formatter
internally).
Format println output in a table
I found a quick and easy way to generate columnar text output in Swift (3.0) using the String method "padding(::)" [In Swift 2.x, the method is named "stringByPaddingToLength(::)"]. It allows you to specify the width of your column, the text you want to use as a pad, and the index of the pad to start with. Works like a charm if you don't mind that it only works with left-aligned text columns. If you want other alignments, you have to buy into the other methods of character counting and other such complexities.
The solution below is contrived to illustrate the utility of the method "padding(::)". Obviously, the best way to leverage this would be to create a function that iterated through a collection to produce the desired table while minimizing code repetition. I did it this way to focus on the task at hand.
Lastly, "println" doesn't seem to exist in Swift 2.x+, so I reverted to "print()".
To illustrate an example using your stated problem:
//Set up the data
let n : Int = 5
let result1 = 1000.0
let result2 = 20000.0
let time1 = "1000ms"
let time2 = "1250ms"
//Establish column widths
let column1PadLength = 8
let columnDefaultPadLength = 12
//Define the header string
let headerString = "n".padding(toLength: column1PadLength, withPad: " ", startingAt: 0) + "result1".padding(toLength: columnDefaultPadLength, withPad: " ", startingAt: 0) + "result2".padding(toLength: columnDefaultPadLength, withPad: " ", startingAt: 0) + "time1".padding(toLength: columnDefaultPadLength, withPad: " ", startingAt: 0) + "time2".padding(toLength: columnDefaultPadLength, withPad: " ", startingAt: 0)
//Define the line separator
let lineString = "".padding(toLength: headerString.characters.count, withPad: "-", startingAt: 0)
//Define the string to display a line of our data
let nString = String(n)
let result1String = String(result1)
let result2String = String(result2)
let dataString = nString.padding(toLength: column1PadLength, withPad: " ", startingAt: 0) + result1String.padding(toLength: columnDefaultPadLength, withPad: " ", startingAt: 0) + result2String.padding(toLength: columnDefaultPadLength, withPad: " ", startingAt: 0) + time1.padding(toLength: columnDefaultPadLength, withPad: " ", startingAt: 0) + time2.padding(toLength: columnDefaultPadLength, withPad: " ", startingAt: 0)
//Print out the data table
print("\(headerString)\n\(lineString)\n\(dataString)")
The output will be printed to your console in a tidy columnar format:
n result1 result2 time1 time2
--------------------------------------------------------
5 1000.0 20000.0 1000ms 1250ms
Changing the variable "columnDefaultPadLength" from 12 to 8 will result in the following output:
n result1 result2 time1 time2
----------------------------------------
5 1000.0 20000.0 1000ms 1250ms
Finally, reducing the padding length to a value less than the data truncates the data instead of generating errors, very handy! Changing the "columnDefaultPadLength" from 8 to 4 results in this output:
n resuresutimetime
------------------------
5 1000200010001250
Obviously not a desired format, but with the simple adjustment of the padding length, you can quickly tweak the table into a compact yet readable form.
How to print in table format using format() method in JAVA?
I think you are trying to print output to the console in an organized format that looks like a table and understand that it is not possible to print exactly like a traditional table with row and column, at least not with simple code with String.format() or System.out.printf().
Looking into your code, what I understand is you are trying to print output that will have 4 columns, a number , it's square, it's cube and it's sqrt respectively.
But before going to that I would like to point out one mistake. From your code it looks like you want to find the sqaure, cube and sqrt of a number from range [lower
, upper
] and your condition for for-loop
satisfies that but however your use of i
is not relevant. I think you have misunderstood the use of iterative variable i
here, the variable i
here is unlike any other normal variable just it has different life span (exists only in the for-loop
block) and it is changed in the last statement of the for-loop
. Futher, I think you do not need this variable i
to achieve your goal.
Below I share two ways to achive that goal, using a for-loop and a while-loop.
Using for-loop:
public static void calc(int upper, int lower) {
System.out.printf("%10s | %10s | %10s | %10s\n", "Number", "Square", "Cube", "Sqrt");
for (; lower <= upper; lower++) {
int square = (int) Math.pow(lower,2);
int cube = (int) Math.pow(lower,3);
double sqrt = Math.sqrt(lower);
System.out.printf("%10d | %10d | %10d | %10f\n", lower, square, cube, sqrt);
}
}
Using while-loop:
public static void calc(int upper, int lower) {
System.out.printf("%10s | %10s | %10s | %10s\n", "Number", "Square", "Cube", "Sqrt");
while(lower <= upper) {
int square = (int) Math.pow(lower,2);
int cube = (int) Math.pow(lower,3);
double sqrt = Math.sqrt(lower);
System.out.printf("%10d | %10d | %10d | %10f\n", lower, square, cube, sqrt);
lower += 1;
}
}
Output calc(8, 4)
(for both codes above):
Number | Square | Cube | Sqrt
4 | 16 | 64 | 2.000000
5 | 25 | 125 | 2.236068
6 | 36 | 216 | 2.449490
7 | 49 | 343 | 2.645751
8 | 64 | 512 | 2.828427
Additional:
If you want to change the right alignment to left alignment then you can just use "-"
as shown below.
public static void calc(int upper, int lower) {
System.out.printf("%-10s | %-10s | %-10s | %-10s\n", "Number", "Square", "Cube", "Sqrt");
while(lower <= upper) {
int square = (int) Math.pow(lower,2);
int cube = (int) Math.pow(lower,3);
double sqrt = Math.sqrt(lower);
System.out.printf("%-10d | %-10d | %-10d | %-10f\n", lower, square, cube, sqrt);
lower += 1;
}
}
Output calc(8, 4)
:
Number | Square | Cube | Sqrt
4 | 16 | 64 | 2.000000
5 | 25 | 125 | 2.236068
6 | 36 | 216 | 2.449490
7 | 49 | 343 | 2.645751
8 | 64 | 512 | 2.828427
Note:
- I used fixed
10 space
here since you declared your variables asint
andint
inJAVA
can take upto10 digits
maximum. Exception is sqrt which is adouble
value and since it is the last value so that will not cause an issue I think.
Reference:
Formatting Numeric Print Output (The Java™ Tutorials > Learning the Java Language > Numbers and Strings)
Formatter (Java Platform SE 8 )
PrintStream (Java Platform SE 8 )
Java println formatting so I can display a table?
Yes, since Java 5, the PrintStream
class used for System.out
has the printf
method, so that you can use string formatting.
Update:
The actual formatting commands depend on the data you are printing, the exact spacing you want, etc. Here's one of many possible examples:
System.out.printf("%1s %-7s %-7s %-6s %-6s%n", "n", "result1", "result2", "time1", "time2");
System.out.printf("%1d %7.2f %7.1f %4dms %4dms%n", 5, 1000F, 20000F, 1000, 1250);
System.out.printf("%1d %7.2f %7.1f %4dms %4dms%n", 6, 300F, 700F, 200, 950);
Formatting Java Output Like a Table
The error is because%d
is for numeric non-floating point values (int
, long
, etc).
In the line where you print the titles, you have to use %XXs
(where XX is a number) since you're passing String
s as parameters:
System.out.format("%10s%15s%15s%15s%20s",
"Grade", "Last Name", "First Name", "Student Number", "Parent Email");
In the line inside the while-loop
, you need to set %d
for the int
and long
variables, like Grade and Student Number, there's no need to convert it to String
using "" + intProperty
:
System.out.format ("%10d%15s%15s%15d%20s",
read.getClass(), read.getLastName(), read.getFirstName(),
read.getStudentNum(), read.getParentEmail());
Since it looks like you want to format the output to the left (and not to the right), you should add a hypen (-) symbol before the XX number:
//similar for title
System.out.format ("%-10d%-15s%-15s%-15d%-20s",
read.getClass(), read.getLastName(), read.getFirstName(),
read.getStudentNum(), read.getParentEmail());
Note: I assumed read.getClass()
and read.getStudentNum()
would return the Grade
and Student number
values as int
or long
.
How to print a table of information in Java
You can use System.out.format(...)
Example:
final Object[][] table = new String[4][];
table[0] = new String[] { "foo", "bar", "baz" };
table[1] = new String[] { "bar2", "foo2", "baz2" };
table[2] = new String[] { "baz3", "bar3", "foo3" };
table[3] = new String[] { "foo4", "bar4", "baz4" };
for (final Object[] row : table) {
System.out.format("%15s%15s%15s%n", row);
}
Result:
foo bar baz
bar2 foo2 baz2
baz3 bar3 foo3
foo4 bar4 baz4
Or use the following code for left-aligned output:
System.out.format("%-15s%-15s%-15s%n", row);
Related Topics
How to Move Application's Window Between Virtual Desktops in Os X
How to Capture Multiple Arguments Weakly in a Swift Closure
Swift Change the Tableviewcell Border Color According to Data
Closure:Use Unresolved Identifier 'Self'
Swift/Cloudkit: After Record Changed, Upload Triggers "Service Record Changed"
Swift Cannot Infer Type from Context
How to Get Frame Data in Apprtc iOS App for Video Modifications
How to Submit Swift 2.2 App with Xcode 7.3 When iOS 10 Is Released
Use of Undeclared Type Autoreleasingunsafepointer Xcode 6 Beta 6
Use of Nspathcontrol to Represent Virtual Path
Solving System of Equations in Swift
Expression Resolves to an Unused Function
How to Split a String into a [String] and Not [Substring]
Create a Navigationlink Without Back Button Swiftui
How to Skip Iterations of a For-In Loop (Swift 3)
Alamofire Returns Wrong Encoding