223k views
4 votes
4.6.1: Reading and outputting strings. Write a program that reads a person's first and last names, separated by a space. Then the program outputs last name, comma, first name. End with newline. Example output if the input is: Maya Jones Jones, Maya

User Rein RPavi
by
8.7k points

1 Answer

3 votes

Answer:

import java.util.Scanner;

public class num5 {

public static void main(String[] args) {

Scanner in = new Scanner(System.in);

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

String name = in.nextLine();

String [ ] n = name.split(" ");

System.out.println(n[0]+", "+n[1]);

}

}

Step-by-step explanation:

Scanner class is used to receive the full names. e.g "Maya Jones"

This is saved in a variable called name using the nextLine() method to grab the entire line of string

The string split() method is used to split the string on the whitespace

The output statement is used to print the value at index 0 and index 1 concatenated with a comma.

User DimitrisCBR
by
8.7k points