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

This program takes user input of a String then calls a method to determine the last character of the String and outputs the result.

My Code

import java.util.Scanner;

public class LastCharacter {

    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("Last character: " + lastCharacter(name));
    }
    public static char lastCharacter(String text){
        return text.charAt(text.length() -1);
        
    }
}

Model Code

import java.util.Scanner;

 

 

public class LastCharacter {

 

    public static char lastCharacter(String text) {

        return text.charAt(text.length() - 1);

 

    }

 

    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("Last character: " + lastCharacter(name));

        

    }

}

Comments

Again, the only difference between my code and the model code is the placement of the method.

Leave a comment