Reputation: 121
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);
}
}
Upvotes: 0
Views: 961
Reputation: 121998
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?
Upvotes: 1