Write code (ReverseNames.java) that prompts the user to enter his or her full name, then prints the name in reverse order (i.e., last name, first name). You may assume that only a first and last name will be given. Here is a sample dialogue with the user:

Respuesta :

Answer:

import java.util.Scanner;

import java.io.*;

public class Main{

    public static void main(String []args){

       

       StringBuilder reversedName = new StringBuilder();

       StringBuilder subName = new StringBuilder();

       

       Scanner myObj = new Scanner(System.in);  // Create a Scanner object

       System.out.println("Enter your full name (last name + first name)");

   

       String name = myObj.nextLine();  // Read user input

       

       for (int i = 0; i < name.length(); i++) {

           

           char currentChar = name.charAt(i);

           

           if (currentChar != ' ') {

               subName.append(currentChar);

           } else {

               reversedName.insert(0, currentChar + subName.toString());

               subName.setLength(0);

           }

       }

       String Resul = reversedName.insert(0, subName.toString()).toString();

       System.out.println("Reverse full name: " + Resul);

    }

}

Explanation:

To solve the problem we used StringBuilder, that allow us to build a string letter by letter, we are using two, one to store temporary information (subName) and the other to store the surname plus name (reversedName). After defining the variables, the program asks for the user fullname using Scanner class and it's method .nextLine (the variable 'name' will save the user input). A while loop is also used to iterate over the name, taking character by character with the method .charAt, the program will append letters in subName until it finds a space only then the content of subName will be transfer to reversedName and the content of subName will be deleted, then the program continues with the process until the end of the for loop; finally, the program places the content of subName at the beginning of reversedName, and print the result transforming the StringBuilder to a normal string.

Ver imagen mateolara11