Hi, one of my labs were doing is a data gatherer, the user enters their first middle and last name all at once with a space between each. then enters there birth month day and year all at once with space between each. Then it outputs them in in a table like fashion with
a each piece having a header... looks like this

First Middle Last
joe frank bob

Day Year Month
1 2010 january

the directions say to use /n /t to align the table properly.... ok so heres MY code

Scanner sc = new Scanner(System.in);
        System.out.print("Enter your first, middle, and last name with a space between each: ");
        String name = sc.nextLine();
        System.out.print("Enter your birth month, birthday, and year with a space between each: ");
        String birth = sc.nextLine();
        System.out.println("First Middle Last");
        System.out.println(name + "\n");
        System.out.println("Month Day Year");
        System.out.println(birth + "\n");

notice how the scanner will read the 3 names... but after that all 3 names are in the string "name" is there a way to assign each name (first, middle and last) its own STRING while being able to enter all 3 on the same line with a space between. Cause with this code when i output it its pretty ugly and doesnt like like a table at all. I need to have a /t between each name and such but i am unable to do that because all the names are in the same string.

7 Years
Discussion Span
Last Post by privinpt

First of all, if you're using "println", it'll put a carriage return at the end of the line. System.out.print() will just output the string, without the carriage return. That'll help you format your output the way you want. There's also printf(), but that's a little complicated, and you don't really need that just now.

Now, if you get a String with Scanner.nextLine() you can use String methods to mess with it. The one you want is split(). Read the Sun documentation for the String class, you'll find the split() method documented there. Briefly, it'll break a String into an array of Strings, splitting it at some character or String that you specify - for example at each ' ' (space character). This will let you break up the input Strings and format them in your table.
Have fun!



String[] nameSegment = name.split();

You can access the first, middle, and last name using the array index. For example to print the middle name you can use:

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.