Skip to content

Mini Project – Exercise 1

Name attributes

  • Project
  • 1 hint
  • 7 of 15 in this chapter

Getting started

Name a project called NameAttributes, and add a scanner to the import list in the project.

The objective

Ask a user for their first and last name. Print out the first name on one line, the last name on the other line. Then write out the amount of letters in said name.

The output should look like this...

Java
Please enter your first and last name
James Smith
Here are your name attributes:
First Name: James
Last Name: Smith
Name Length: 10

Hints

Hint 1‌‌

‌‌

Solution

Solution – Exercise 1

The solution

here is the solution...

Java
import java.util.Scanner;
public class NameAttributes {
 public static void main(String[] args) {
 Scanner userInput = new Scanner(System.in);
 System.out.println("Please enter your first and last name");
 String name = userInput.nextLine();
 userInput.close();
 int length = name.length()-1;
 int spaceIndex = name.indexOf(" ");
 String firstName = name.substring(0, spaceIndex);
 String lastName = name.substring(spaceIndex, length+1);
 System.out.println("Here are your name attributes:");
 System.out.println("First Name: " + firstName);
 System.out.println("Last Name: " + lastName);
 System.out.println("Name Length: " + length);
 }
}

Give the project a try first.