0

My question concerns the indentation of the results specifically. Some are String and some double. So far I have the following java program shown at the below. I need the following result:

Name:             Yoda Luca
Income:           %5000.00
Interests:        Swimming, Hiking

I don't want to have to write a prefix for every line. Is there a quicker way to format once for "String" and once for "Double" ?

Program:

import java.util.Scanner;

public class forTesting {
    public static void main(String[] args) {
        String prefixName = "Name:"; 
        String prefixIncome = "Income";

        String Name;
        double Income;

        //create a Scanner that is connected to System.in
        Scanner input = new Scanner(System.in);

        System.out.print("Enter name:");
        Name = input.nextLine();

        System.out.print("Enter income for period: ");
        Income = input.nextDouble();

        String format = "%-40s%s%n"; 
        System.out.printf(format, prefixName,Name);
        System.out.printf(format, prefixIncome, Income);
    }
}
Corey
  • 1,217
  • 3
  • 22
  • 39
yoda
  • 121
  • 1
  • 9
  • Just for the record: in the real world you don't use floating point numbers to represent currency. So if you are working with real data about real money, do NOT use TV float here! – GhostCat Mar 18 '17 at 05:35

1 Answers1

1

String format takes format and followed by n number of arguments.

Yes. %f is for double and you can write them in one shot.

String format = "%-40s%s%n%-40s%f%n";
System.out.printf(format, prefixName,Name,prefixIncome, Income);

And that gives you floating point double. To get it in standard format

How to nicely format floating numbers to String without unnecessary decimal 0?

Community
  • 1
  • 1
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
  • thanks ANS. if i then want to format the number to two decimal places, where do i do this? – yoda Mar 18 '17 at 05:48