Write code to take a String input from the user, then print the first and last letters of the string on one line. Sample run: Enter a string: surcharge se Hint - we saw in the lesson how to get the first letter of a string using the substring method. Think how you could use the .length() String method to find the index of the last character, and how you could use this index in the substring method to get the last character.

Respuesta :

Answer:

//import the Scanner class to allow for user input

import java.util.Scanner;

//Begin class definition

public class FirstAndLast{

   //Begin the main method

    public static void main(String []args){

       

       

       //****create an object of the Scanner class.

       //Call the object 'input' to receive user's input

       //from the console.

       Scanner input = new Scanner(System.in);

       

       //****create a prompt to tell the user what to do.

       System.out.println("Enter the string");

       

       //****receive the user's input

       //And store it in a String variable called 'str'

       String str =  input.next();

       

       //****get and print the first character.

       //substring(0, 1) - means get all the characters starting

       //from the lower bound (index 0) up to, but not including the upper

       //bound(index 1).

       //That technically means the first character.

       System.out.print(str.substring(0,1));

       

       //****get and print the last character

       //1. str.length() will return the number of character in the string 'str'.

       //This is also the length of the string

       //2. substring(str.length() - 1) - means get all the characters starting

       // from index that is one less than the length of the string to the last

       // index (since an upper bound is not specified).

       // This technically means the last character.

       System.out.print(str.substring(str.length()-1));

       

       

       

    }  // end of main method

   

} //end of class definition

Explanation:

The code has been written in Java and it contains comments explaining important parts of the code. Kindly go through the comments.

The source code and a sample output have also been attached to this response.

To run this program, copy the code in the source code inside a Java IDE or editor and save it as FirstAndLast.java

Ver imagen stigawithfun
Ver imagen stigawithfun