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

This program takes a string input and then calls a method to calculate the string length and return it for display.

My Code

import java.util.Scanner;

public class LengthOfName {
    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);
        // call your method from here
        System.out.print("Type your name: ");
        String name = reader.nextLine();
        System.out.println("Number of characters: " + calculateCharacters(name));
        
    }
    
    // do here the method
    // public static int calculateCharacters(String text)
    public static int calculateCharacters(String text){
        return text.length();
    }
    
}

Model Code

import java.util.Scanner;

 

public class LengthOfName {

    public static void main(String[] args) {

        Scanner reader = new Scanner(System.in);

        // call your method from here

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

        String name = reader.nextLine();

        System.out.print("Number of characters: " + calculateCharacters(name));

    }

    

    // do here the method

    // public static int calculateCharacters(String text)

    

    public static int calculateCharacters(String text) {

        return text.length();

    }

}

Comments

Both my code and the model code are exactly the same.

Leave a comment