Object-Oriented Programming with Java, part I – Exercise 48

This program take the user input of a name and then calls a method that returns the first letter of that name to be displayed.

My Code

import java.util.Scanner;

public class FirstCharacter {

    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);
        System.out.print("Type your name: ");
        String name = reader.nextLine();
        System.out.println("First character: " + firstCharacter(name));

    }

    public static char firstCharacter(String text) {
        return text.charAt(0);
    }
}

Model Code

import java.util.Scanner;

 

public class FirstCharacter {

    public static char firstCharacter(String text) {

        return text.charAt(0);

 

    }

 

    public static void main(String[] args) {

        Scanner reader = new Scanner(System.in);

        System.out.print("Type your name ");

        String name = reader.nextLine();

        System.out.println("First character: " + firstCharacter(name));

    }

}

Comments

Although my code and the model code are the same, the model code has the method before the main program whereas mine has it afterwards. This is opposite to the model code in the prior question so I am going to assume it is a matter of taste or readability.

Leave a comment