101k views
3 votes
Write a method called processName that accepts a Scanner for the console as a parameter and 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. You should read the entire line of input at once with the Scanner and then break it apart as necessary. Here is a sample dialogue with the user:

Output:Please enter your full name: Sammy JankisYour name in reverse order is Jankis, Sammywhat I have:public static void processName(Scanner in){System.out.print("Please enter your full name: ");String Name = in.nextLine();String lastName= in.subString(6,11);String firstName= in.subString(0,5);System.out.println("Your name in reverse order is " + lastName + ", " + firstName);}

User Hkon
by
5.5k points

1 Answer

3 votes

Answer:

Complete definition of method processName is as follows:

public static void processName(Scanner in){

System.out.println("Please enter your full name: ");

String Name = in.nextLine();

String [] strings = Name.split(" ");

String firstName = strings[0];

String lastName = strings[1];

System.out.println("Your name in reverse order is " + lastName+ " "+ firstName);

}

Step-by-step explanation:

Here subString method is not useful to break the string into first name and last name.

The better idea is to use the spilt(); function of string. split() function is used to split the given string into two halves depending on the delimiter passed as argument.

In the above method blank space (" ") is passed as delimiter. Thus split function stores the first half of string before blank space in strings array at location 0 and 1 respectively.

Sample program to implement above method:

import java.util.Scanner;

public class Main{

public static void main(String [] args)

{

Scanner in = new Scanner(System.in);

processName(in);

}

public static void processName(Scanner in){

System.out.println("Please enter your full name: ");

String Name = in.nextLine();

String [] strings = Name.split(" ");

String firstName = strings[0];

String lastName = strings[1];

System.out.println("Your name in reverse order is " + lastName+ " "+ firstName);

}

}

Sample output:

Please enter your full name:

Jim hoppers

Your name in reverse order is hoppers Jim

User Harrythomas
by
5.7k points