LPSanz LPSanz - 14 days ago 9
Java Question

Printing 2 headers on 2 tables

Good morning everyone,

I was assigned to get a 2 sided table displayed on java (beginner). I was able to get the body of the table but I'm having trouble coding to get the table headers printed. The first column should have "Miles" as header and the second column should have "Kilometers" as header. How do I get this to print?

Below is the code I've done for the output of the table.

//This program will display 2 tables side by side
//With the use of for or while loop structure

import java.util.Scanner;
public class Lab5
{
public static void main(String[] args)
{
final double MILES_PER_KM = 1.61; // miles per km
double kilometers = MILES_PER_KM;



for (int miles = 1; miles <= 11; miles +=2)
{
double km = miles * MILES_PER_KM;
String s = String.format("%3d\t%3.2f", miles, miles*MILES_PER_KM);
System.out.println(s);
}


}//main

}//class

Answer

I would just use printf() and something like this,

final double MILES_PER_KM = 1.61; // miles per km
System.out.printf("%s\t%s%n", "Miles/hr", "Km/hr");
for (int miles = 1; miles <= 11; miles += 2) {
    double km = miles * MILES_PER_KM;
    System.out.printf("%3d\t\t%3.2f%n", miles, miles * MILES_PER_KM);
}