formatting - Printf not functioning properly in Java 1.7 -
i'm doing assignment school requires program users personal information through various methods(last name, first name, address, etc.) , output them through main method.
problem: printf statement works fine when displaying name, when displays rest of users information, won't format properly.
import java.util.scanner; public class personalinfo { public static string lastname, firstname, address, email, phone; public static scanner kb = new scanner(system.in); public static void main(string[] args) { getlastname(); getfirstname(); getaddress(); getemail(); getphone(); displayname(); displayaddress(); displayemailphone(); } //--------get methods-------- public static void getlastname() { system.out.print("what last name of user? "); lastname = kb.nextline(); } public static void getfirstname() { system.out.print("now enter first name: "); firstname = kb.nextline(); } public static void getaddress() { system.out.print("now enter address: "); address = kb.nextline(); } public static void getemail() { system.out.print("now enter email: "); email = kb.nextline(); } public static void getphone() { system.out.print("lastly, enter phone number in format xxx-xxx- xxxx: "); phone = kb.nextline(); } //--------display methods-------- public static void displayname() { system.out.printf("\nname:%15s %s", firstname, lastname); } public static void displayaddress() { system.out.printf("\naddress:%12s", address); } public static void displayemailphone() { system.out.printf("\nemail:%14s", email); system.out.printf("\nphone:%14s", phone); } }
output results:
name: john smith address:1234 street, city, state 12345 email:useremail@email.com phone: 123-456-7890
what problem? want rest of information line name.
so when "%15s" you're saying make field 15 characters wide, prepended spaces if need be. works name - there's bunch of spaces , name.
the address, though, far more 14 characters, no spaces in front of it. (note not truncate @ 14; 14 minimum width here.)
you haven't defined mean "line up" though... want "1234" directly under "john"? in case, need add spaces printf string, , skip width specifiers (change "%s" instead of "%15s").
if instead, want zip code "12345" under "smith", you'll need vastly increase width specifiers. width specifier plus prefix ("name:" or "address:") need add same number. example, use "%50s" name , use "%47s" address (since there 3 more characters in "address:" there in "name:").