Java Homework Help

Discussion in 'Mac Programming' started by 103734, Jan 23, 2010.

  1. 103734 Guest

    Joined:
    Apr 10, 2007
    #1
    I wrote a simple program for homework and I am having a small problem. I need it to print "First Middle Last" but it is printing "FirstMiddleLast" I am trying to figure out how to space them out but I just can't think right now, I know its something simple. The code is.

    Code:
    import java.util.Scanner;
    
    public class Story
    {
            public static void main(String[] args)
            {
                    String firstName, midName, lastName, favColor;
                    int age, luckyNum;
                    Scanner keyboard = new Scanner (System.in);
    
                    System.out.print("What is your first name? ");
                    firstName = keyboard.nextLine();
                    System.out.print("What is your middle name? ");
                    midName = keyboard.nextLine();
                    System.out.print("What is your last name? ");
                    lastName = keyboard.nextLine();
                    System.out.print("How old are you? ");
                    age = keyboard.nextInt();
                    keyboard.nextLine();
                    System.out.print("What is your lucky number? ");
                    luckyNum =  keyboard.nextInt();
                    keyboard.nextLine();
                    System.out.print("What is your favorite color? ");
                    favColor = keyboard.nextLine();
    
                    String initials = firstName.substring(0,1) +
                    midName.substring(0,1) + lastName.substring(0,1);
    
                    System.out.println(firstName + " is " + age + " years old.\nThe initials of "
                    + firstName + midName + lastName + " are " + initials + ".\n" + initials +
                    "'s favorite color is " + favColor + " and the lucky number is " + luckyNum + ".");
            }
    }
    
    I thought maybe I could declare a new string like "fullName = firstName + midName + lastName" but its the same thing.
     
  2. 103734 thread starter Guest

    Joined:
    Apr 10, 2007
    #2
    Code:
    System.out.println(firstName + " is " + age + " years old.\nThe initials of "
                    + firstName + " " + midName + " " + lastName + " are " + initials + ".\n" + initials +
                    "'s favorite color is " + favColor + " and the lucky number is " + luckyNum + ".");
            }
    I knew it would be simple, someone can delete this.
     
  3. Daveoc64 macrumors 601

    Joined:
    Jan 16, 2008
    Location:
    Bristol, UK
    #3
    Yup.

    You have to remember that spaces outside of quotes wont impact on Strings.
     

Share This Page