public class Test {
public static void main(String[] args) {
String name = "John King IV. Cena";
int start = name.indexOf(' ');
int end = name.lastIndexOf(' ');
String firstName = "";
String middleName = "";
String lastName = "";
if (start >= 0) {
firstName = name.substring(0, start);
if (end > start)
middleName = name.substring(start + 1, end);
lastName = name.substring(end + 1, name.length());
}
System.out.println(firstName);
System.out.println(middleName);
System.out.println(lastName);
}
}
In above code I dont want middle name. I want to get full name from user then it has to split like firstname and lastname.
You can try String'ssplit method to do this:
String name = "John King IV. Cena";
String []nameArray=name.split("\\s+");
System.out.println("FirstName "+nameArray[0] );
System.out.println("LastName "+nameArray[nameArray.length-1]);
Related
Currently stuck on an assignment that requires me to print out the users name as such: Last,First Initial.
(Bob, Billy H.) If I add too many spaces between the first and middle name when inputting, I get an index out of bounds exception. (String out of bounds 0) The program runs completely fine unless I have more than one space between the first and middle name.
I can only use the trim, indexOf, substring,and charAt methods in this program.
import java.util.Scanner;
public class Name {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter your name in this format: <spaces>First name<spaces>Middle name<spaces>Last name<spaces>");
String name = s.nextLine();
name = name.trim();
String first, middle, last;
int firstSpace = name.indexOf(' ');
first = name.substring(0, firstSpace);
int secondSpace = name.indexOf(" ", (firstSpace + 1));
middle = name.substring((firstSpace + 1), secondSpace);
middle.trim();
last = name.substring(secondSpace+1);
char middleInitial = middle.charAt(0);
String initial = "";
initial = initial + middleInitial;
for(int i = 1; i < middle.length(); i++) {
char currentLetter = middle.charAt(i);
char lastLetter = middle.charAt(i - 1);
if(lastLetter == ' ') {
initial = initial + "." + currentLetter;
}
}
System.out.println(last + "," + first + ' ' + initial + ".");
}
}
The reason for error is for input
amid skum asdf
for above input:
int firstSpace = name.indexOf(' '); //firstSpace = 0
int secondSpace = name.indexOf(" ", (firstSpace + 1));//secondSpace = 1
middle = name.substring((firstSpace + 1), secondSpace); // as the two or more continues space inputted, this will select empty string as firstSpace + 1 == secondSpace and later causing the exception
Do name = name.replaceAll(" +", " "); to replace all two or more white spaces.
As karthik suggested in comments, perform assignment middle = middle.trim();.
EDIT:
Since you can not use replaceAll, Modified the code just by using trim method. Have a closer look at the below snippets:
String middleNameLastName = name.substring(firstSpace+1).trim();
last = middleNameLastName.substring(index+1).trim();
These removes trailing spaces.
import java.util.Scanner;
public class Post1 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter your name in this format: <spaces>First name<spaces>Middle name<spaces>Last name<spaces>");
String name = s.nextLine();
name = name.trim();
String first, middle, last;
int firstSpace = name.indexOf(' ');
first = name.substring(0, firstSpace);
String middleNameLastName = name.substring(firstSpace+1).trim();
int index = middleNameLastName.indexOf(" ");
middle = middleNameLastName.substring(0, index);
last = middleNameLastName.substring(index+1).trim();
System.out.println(last + "," + first + ' ' + middle.charAt(0) + ".");
s.close();
}
}
How do I get the program to accept a surname less than 5 characters for example joe cole would be jcole.
public void names(String firstName, String surname) {
String userIdentity = firstName.substring(0,1) + surname.substring(0,5);
System.out.println(userIdentity.toLowerCase());
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
UserId name = new UserId();
String first;
String last;
System.out.println("Enter first name: ");
first = scan.next();
System.out.println("Enter surname: ");
last = scan.next();
name.names(first, last);
scan.close();
}
You can use Math.min(int, int) to get the lesser value of 5 and the surname.length(). Something like,
public void names(String firstName, String surname) {
String userIdentity = firstName.substring(0,1) //
+ surname.substring(0, Math.min(surname.length(), 5));
System.out.println(userIdentity.toLowerCase());
}
Instead of
String userIdentity = firstName.substring(0,1) + surname.substring(0,5);
Only create a substring if the name is long enough.
String userIdentity = firstName.substring(0,1) +
surname.substring(0,(surname.length >= 5) ? 5 : surname.length);
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have written a code which separates first name and last name in a name String:
public class NameSeperator {
public static void main(String[] args)
{
String custName="Your Name";
int index;
String firstName;
index=custName.indexOf(" ");
**int last=custName.lastIndexOf("")**;
firstName=custName.substring(0,index);
String lastName=custName.substring(index+1,last);
// get the first name
System.out.println("First Name = "+firstName);
System.out.println("Last Name = "+lastName);
}
}
I have used
int last=custName.lastIndexOf("")
and used only "" here but it takes complete string here.Is "" means the complete string at which a particular string method is called?
You can directly split it by space and then use array index
String name[] = custName.split(" ");
String firstName = name[0];
String lastName = name[1]
I would recommend this simplified version :
int index = custName.indexOf(' ');
String firstName = custName.substring(0, index);
String lastName = custName.substring(index + 1);
Note that indexOf searches for a single character. Also the second substring for lastName gets the remaining chars until the end.
Modify your code :
String custName="Your Name";
int start = custName.indexOf(' ');
int end = custName.lastIndexOf(' ');
String firstName = "";
String middleName = "";
String lastName = "";
if (start >= 0) {
firstName = custName.substring(0, start);
if (end > start)
middleName = custName.substring(start + 1, end);
lastName = custName.substring(end + 1, custName.length());
}
System.out.println("First Name = "+firstName);
System.out.println("Middle Name = "+middleName);
System.out.println("Last Name = "+lastName);
I'm struggling with this code. Return of this one is eg: "JS John Smith" but when I try to put two names plus surname all I get is a mess. I wish to get when I type eg: "John William Smith" something like this: "JW Smith", anybody know hot to do it?
import java.io.*;
import java.io.BufferedReader;
public class ex54 {
public static void main(String[] args) {
System.out.print("Enter your name: ");
BufferedReader br = new BufferedReader(new InputStreamReader (System.in));
String fullName = null;
try{
fullName = br.readLine();
} catch (IOException ioe) {
System.out.println("Error");
System.exit(1);
}
int spacePos = fullName.indexOf(" ");
// String firstName = fullName.substring(0, spacePos);
// String secondName = fullName.substring(1, spacePos);
String firstInitial = fullName.substring(0, 1);
String secondInitial = fullName.substring(spacePos+1, spacePos+2);
String userName = (firstInitial + secondInitial + " ").concat(fullName);
System.out.println("Hello, your user name is: " + userName);
}
}
}
You can split the name, assuming you are given a three-name string:
String[] names = fullname.split(" ");
System.out.println("" + names[0].charAt(0) + names[1].charAt(0) + " " + names[2]);
int spacePos = -1;
System.out.print("Hello, your user name is:");
do {
System.out.print(" "+fullName.substring(spacePos+1, spacePos+2));
fullName = fullName.substring(spacePos+1);
spacePos = fullName.indexOf(" ");
}while(spacePos != -1);
System.out.println("\b"+fullName);
Just for kicks, here is an implementation using regular expressions:
private static String firstNamesToInitials(String name) {
StringBuilder buf = new StringBuilder();
Matcher m = Pattern.compile("\\b([A-Z])[A-Za-z]*\\b").matcher(name);
String lastName = null;
while (m.find()) {
buf.append(m.group(1));
lastName = m.group();
}
if (buf.length() <= 1)
return lastName;
buf.setCharAt(buf.length() - 1, ' ');
return buf.append(lastName).toString();
}
Test
System.out.println(firstNamesToInitials("Cher"));
System.out.println(firstNamesToInitials("John Smith"));
System.out.println(firstNamesToInitials("John William Smith"));
System.out.println(firstNamesToInitials("Charles Philip Arthur George"));
System.out.println(firstNamesToInitials("Pablo Diego José Francisco de Paula Juan Nepomuceno María de los Remedios Cipriano de la Santísima Trinidad Ruiz y Picasso"));
Output
Cher
J Smith
JW Smith
CPA George
PDFPJNRCTR Picasso
I created a program which will parse the firstName, middleName and lastName. Here is the program and output. This program can definitely be improved and need some input on reducing my cumbersome ugly code and replace it with a better one. Any suggestions or example ?
public class Test {
public static void main(String[] args) {
String fullName = "John King IV. Cena";
String[] tokens = fullName.split(" ");
String firstName = "";
String middleName = "";
String lastName = "";
if(tokens.length > 0) {
firstName = tokens[0];
middleName = tokens.length > 2 ? getMiddleName(tokens) : "";
lastName = tokens[tokens.length -1];
}
System.out.println(firstName);
System.out.println(middleName);
System.out.println(lastName);
}
public static String getMiddleName(String[] middleName){
StringBuilder builder = new StringBuilder();
for (int i = 1; i < middleName.length-1; i++) {
builder.append(middleName[i] + " ");
}
return builder.toString();
}
}
John
King IV.
Cena
This code does the same, but doesn't keep a trailing space in the middle name. This is one of several possible cleaner implementations.
public class Test {
public static void main(String[] args) {
String name = "John King IV. Cena";
int start = name.indexOf(' ');
int end = name.lastIndexOf(' ');
String firstName = "";
String middleName = "";
String lastName = "";
if (start >= 0) {
firstName = name.substring(0, start);
if (end > start)
middleName = name.substring(start + 1, end);
lastName = name.substring(end + 1, name.length());
}
System.out.println(firstName);
System.out.println(middleName);
System.out.println(lastName);
}
}
As the guys said, next time go directly to https://codereview.stackexchange.com/
The algorithm will fail if the persons last name has more than one word, like Abraham Van Helsing. Van is not a middle name but part of the last name.
Obviously, there is no algorithm to clearly distinguish between middle name and last name in general. We always have to guess and we can only try to improve the probability that the guess is correct, maybe be checking middle name parts against word or filter lists.
You could also use a StringTokenizer for this:
import java.util.StringTokenizer;
public class Test {
public static void main(String[] args) {
String fullName = "John King IV. Cena";
StringTokenizer stok = new StringTokenizer(fullName);
String firstName = stok.nextToken();
StringBuilder middleName = new StringBuilder();
String lastName = stok.nextToken();
while (stok.hasMoreTokens())
{
middleName.append(lastName + " ");
lastName = stok.nextToken();
}
System.out.println(firstName);
System.out.println(middleName.toString().trim());
System.out.println(lastName);
}
}
Update the code to handle where there is no last name i.e. user enters only the first name like "Mark"
if(tokens.length > 0) {
firstName = tokens[0];
middleName = tokens.length > 2 ? getMiddleName(tokens) : "";
if(tokens.length > 1){
lastName = tokens[tokens.length -1];
}
}