For example the name Donald trump (12 character) brings up the error string index out of range 7 (where the space is found) even though the name Donald trump is longer.
package test;
import javax.swing.JOptionPane;
public class Usernamesubstring {
public static void main(String[] args) {
String fullname = JOptionPane.showInputDialog("What is your full name");
int breakbetween = fullname.lastIndexOf(" ");
String firstnamess = fullname.substring(breakbetween - 3, breakbetween);
int length = fullname.length();
String lastnamess = fullname.substring(length - 3, length);
String firstnamec = firstnamess.substring(0, 0);
String lastnamec = lastnamess.substring(breakbetween + 1, breakbetween + 1 );
firstnamec = firstnamec.toUpperCase();
lastnamec = lastnamec.toUpperCase();
String firstname = firstnamess.substring(1,3);
String lastname = firstnamess.substring(1,3);
firstname = firstnamec + firstname;
lastname = lastnamec + lastname;
System.out.println(firstname + lastname);
}
}
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 7
at java.lang.String.substring(String.java:1963)
at test.Usernamesubstring.main(Usernamesubstring.java:14)
You've made it more complicated than it needs to be. A simple solution can be made using String.split (which divides a string into an array of smaller strings based on a delimiter, e.g. "Donald Trump".split(" ") == {"Donald", "Trump"})
Full Code
class Usernamesubstring // change that since it no longer uses substrings
{
public static void main (String[] args)
{
String fullName = "Donald Trump";
String[] parts = fullName.split(" ");
String firstName = parts[0]; // first item before the space
String lastName = parts[parts.length - 1]; // last item in the array
System.out.println(firstName + " " + lastName);
}
}
sometimes independent of your indexes
String fullName = "Donald Trump";
String[] result = fullName.split (" ");
in result you will find now
result [0] ==> Donald
result [1] ==> Trump
isn't that a little easier for your project?
Your error shoul be in the line String lastnamec = lastnamess.substring(breakbetween + 1, breakbetween + 1 ); as lastnamess is a string of lenght 3 from fullname.substring(length - 3, length); and breakbetween is greater then 3 for "Donald Trump", where space is character 6.
You should simpify your code a bit, it makes it easier to read and find the problems.
tl;dr: The exception occurs when you try to access a String at an index which exceeds it's length or is just not contained in the string (negative values).
Regarding your approach: It's usually not a good idea to prompt a name in full because people tend to input weird stuff or mix up the order. Better prompt for first and last name separately.
Assuming someone input his name with Firstname Lastname you wouldn't have to make such a substring mess, Java has some nice features:
String name = "Mario Peach Bowser";
name = name.trim();
String[] parts = name.split(" ");
String lastname = parts[parts.length-1];
String firstname = name.replace(lastname, "").trim();
System.out.println("Hello "+firstname+", your last name is: "+lastname);
In this case I am using the trim() function to remove whitespaces at the start and end and just split the string when a white space occurs. Since people can have some middle names and stuff, I just replace the last name out of the raw input string, call trim() on it again and you have everything extracted.
If you really want a substring approach, the following would work:
String lastname = name.substring(name.lastIndexOf(" ")).trim();
String firstname = name.substring(0,name.lastIndexOf(" ")).trim();
You usually don't store the index variables. But each variant would need some sort of error check, you can either use try{} and catch() or check the String before parsing.
Only these lines are required.
String[] nameArr = fullname.split(" ");
String lastN = nameArr[nameArr.length - 1];
int lastIndexOf = fullname.lastIndexOf(lastN);
String firstN = fullname.substring(0, lastIndexOf);
System.out.println(firstN + " " + lastN);
Related
example of output should be
please help thank you in advance!!
the output of the code in username should be the 2 letter in firt name and 3 in last name and date number
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.println("Enter Fullname:");
String fullname = sc.nextLine();
System.out.println("Enter Birthday : ");
String bday = sc.nextLine();
System.out.println("Your Login Details");
System.out.println("Enter Fullname:" + fullname);
System.out.println("Enter Birthday : " + bday);
System.out.println("Enter Username: " + );
}
}
Assuming the input will always be in the format you provided, you can use String.split() and String.substring() to extract the required information from the input as shown below.
String[] splitName = fullName.split(" ");
String firstName = splitName[0];
String lastName = splitName[1];
String day = bday.split("-")[1];
String username = firstName.substring(0, 2) + lastName.substring(0, 3) + day;
You can use this code to achieve the expected result. The name should always be in this format FirstName LastName, otherwise, you may encounter NullPointerException more frequently. There are split and substring methods in the string class. Follow these steps to get started
Full name should be split into two strings, the first is for the first name and another is for the last name, for this we will use the split method which returns String[].
After splitting the full name, the substring method comes into the picture, substring method takes two parameters first and the last index. We can use this method with both strings received by the split method.
String[] firstLastName = fullname.split(" ");
System.out.println("Enter Username: " + firstLastName[0].substring(0, 2) + firstLastName[1].substring(0, 3) + bday.split("-")[1]);
Syntax
Public String [] split ( String regex, int limit)
public String substring(int begIndex, int endIndex)
String str = "FirstName LastName - 1234xx"
In above case, want to replace above string with everything after " - " substring. In the above example it would mean changing str to 1234xx
The length of string after " - " is not fixed, hence cannot just capture last certain no. of characters
This approach gives FirstName LastName - - instead of desired output 1234xx
public class StringExample
{
public static void main(String[] args)
{
String str = "FirstName LastName - 1234xx";
String newStr = str.replaceAll("(?<=( - )).*", "$1");
System.out.println(newStr);
}
}
You were on the right track. Just use a lazy dot to consume everything up to and including the dash.
String str = "FirstName LastName - 1234xx";
String newStr = str.replaceAll("^.*-\\s*", "");
System.out.println(newStr);
This question already has answers here:
Remove all occurrences of char from string
(13 answers)
Closed 5 years ago.
I was wondering how to ignore spaces in Java. This program allows you to enter your first, middle and surname which then outputs your initials. I'm now trying to make it ignore any white spaces. Thanks in advance!
String fullName;
char firstName;
char secondName;
char surname;
int space1;
int space2;
System.out.println("Please enter your first name, your second name and your surname: ");
fullName = kybd.nextLine();
firstName = fullName.charAt(0);
space1 = fullName.indexOf(" ");
secondName = fullName.charAt(space1 + 1);
space2 = fullName.lastIndexOf(" ");
surname = fullName.charAt(space2 + 1);
System.out.println("Initials: " + firstName + secondName + surname);
Explanation
You can implicitly ignore them by just removing them from your input text.
Therefore replace all occurrences with "" (empty text):
fullName = fullName.replaceAll(" ", "");
After that call fullName won't contain a whitespace anymore.
However you'll then get a problem with your logic as you split on whitespaces.
Solution
An alternative could be to first trim the text (removing leading and trailing whitespaces). Then do your split and after that you can remove all other whitespaces:
fullName = kybd.nextLine();
// Remove leading and trailing whitespaces
fullName = fullName.trim();
// Bounds
firstSpace = fullName.indexOf(" ");
lastSpace = fullName.lastIndexOf(" ");
// Extract names
String fullFirstName = fullName.substring(0, firstSpace);
String fullSecondName = fullName.substring(firstSpace + 1, lastSpace);
String fullSurname = fullName.substring(lastSpace + 1);
// Trim everything
fullFirstName = fullFirstName.trim(); // Not needed
fullSecondName = fullSecondName.trim();
fullSurname = fullSurname.trim();
// Get initials
firstName = fullFirstName.charAt(0);
secondName = fullSecondName.charAt(0);
surname = fullSurname.charAt(0);
Example
Let's take a look at an example input (_ stands for whitespace):
__John___Richard_Doe_____
We will first trim fullName and thus get:
John___Richard_Doe
Now we identify the first and the last whitespace and split on them:
First name: John
Second name: ___Richard
Surname: _Doe
Last we also trim everything and get:
First name: John
Second name: Richard
Surname: Doe
With charAt(0) we access the initials:
First name: J
Second name: R
Surname: D
More dynamic
Another more dynamic approach would be to merge all successive whitespaces into a single whitespace. Therefore you would need to traverse the text from left to right and start recording once you see a whitespace, end recording if visiting a non-whitespace character, then replace that section by a single whitespace.
Our example then is:
_John_Richard_Doe_
And after an additional trim you can use your regular approach again:
John_Richard_Doe
Or you can use split(" ") and then reject every empty String:
Iterator<String> elements = Pattern.compile(" ").splitAsStream(fullName)
.filter(e -> !e.isEmpty()) // Reject empty elements
.collect(Collectors.toList()) // Collect to list
.iterator() // Iterator
firstName = elements.next().charAt(0);
secondName = elements.next().charAt(0);
surname = elements.next().charAt(0);
Using the example again the Stream first consists of
"", "", "John", "", "", "Richard", "Doe", "", "", "", "", ""
after the filtering it's
"John", "Richard", "Doe"
Minus Sign
As you said you also want
Richard Jack Smith-Adams
output RJS-A, you can simply split on - after splitting on the whitespace.
Pattern spacePatt = Pattern.compile(" ");
Pattern minusPatt = Pattern.compile("-");
String result = spacePatt.splitAsStream(fullName) // Split on " "
.filter(e -> !e.isEmpty()) // Reject empty elements
.map(minusPatt::splitAsStream) // Split on "-"
.map(stream ->
stream.map(e -> e.substring(0, 1))) // Get initials
.map(stream ->
stream.collect(Collectors.joining("-"))) // Add "-"
.collect(Collectors.joining("")); // Concatenate
Which outputs RJS-A.
This approach is a bit more complicated as we need to maintain the information of the sub-streams, we can't just flatMap everything together, otherwise we wouldn't know where to add the - again. So in the middle part we are indeed operating on Stream<Stream<String>> objects.
I think what you're after here is the split method in String
Which you could use like this:
String fullName = "John Alexander Macdonald";
String[] split = fullName.split(" "); // ["John", "Alexander", "Macdonald"]
The other thing you might want is the trim method which removes spaces from the front and the back of a string.
String withSpaces = " a b c ";
String trimmed = withSpace.trim(); // "a b c"
I'm writing out a piece of a code that where I am trying to split up the user's input into 3 different arrays, by using the spaces in-between the values the user has entered. However, everytime i run the code i get the error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at Substring.main(Substring.java:18)
Java Result: 1
I have tried to use a different delimiter when entering the text and it has worked fine, e.g. using a / split the exact same input normally, and did what i wanted it to do thus far.
Any help would be appreciated!
Here's my code if needed
import java.util.Scanner;
public class Substring{
public static void main(String[]args){
Scanner user_input = new Scanner(System.in);
String fullname = ""; //declaring a variable so the user can enter their full name
String[] NameSplit = new String[2];
String FirstName;
String MiddleName;
String LastName;
System.out.println("Enter your full name (First Middle Last): ");
fullname = user_input.next(); //saving the user's name in the string fullname
NameSplit = fullname.split(" ");//We are splitting up the value of fullname every time there is a space between words
FirstName = NameSplit[0]; //Putting the values that are in the array into seperate string values, so they are easier to handle
MiddleName = NameSplit[1];
LastName = NameSplit[2];
System.out.println(fullname); //outputting the user's orginal input
System.out.println(LastName+ ", "+ FirstName +" "+ MiddleName);//outputting the last name first, then the first name, then the middle name
new StringBuilder(FirstName).reverse().toString();
System.out.println(FirstName);
}
}
Split is a regular expression, you can look for one or more spaces (" +") instead of just one space (" ").
String[] array = s.split(" +");
Or you can use Strint Tokenizer
String message = "MY name is ";
String delim = " \n\r\t,.;"; //insert here all delimitators
StringTokenizer st = new StringTokenizer(message,delim);
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
You have made mistakes at following places:
fullname = user_input.next();
It should be nextLine() instead of just next() since you want to read the complete line from the Scanner.
String[] NameSplit = new String[2];
There is no need for this step as you are doing NameSplit = user_input.split(...) later but it should be new String[3] instead of new String[2] since you are storing three entries i.e. First Name, Middle Name and the Last Name.
Here is the correct program:
class Substring {
public static void main (String[] args) throws java.lang.Exception {
Scanner user_input = new Scanner(System.in);
String[] NameSplit = new String[3];
String FirstName;
String MiddleName;
String LastName;
System.out.println("Enter your full name (First Middle Last): ");
String fullname = user_input.nextLine();
NameSplit = fullname.split(" ");
FirstName = NameSplit[0];
MiddleName = NameSplit[1];
LastName = NameSplit[2];
System.out.println(fullname);
System.out.println(LastName+ ", "+ FirstName +" "+ MiddleName);
new StringBuilder(FirstName).reverse().toString();
System.out.println(FirstName);
}
}
Output:
Enter your full name (First Middle Last): John Mayer Smith
Smith, John Mayer
John
java.util.Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
hence even though you entered 'Elvis John Presley' only 'Elvis' is stored in the fullName variable.
You can use BufferedReader to read full line:
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
try {
fullname = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
or you can change the default behavior of scanner by using:
user_input.useDelimiter("\n"); method.
The exception clearly tells that you are exceeding the array's length. The index 2 in LastName = NameSplit[2] is out of array's bounds. To get rid of the error you must:
1- Change String[] NameSplit = new String[2] to String[] NameSplit = new String[3] because the array length should be 3.
Read more here: [ How do I declare and initialize an array in Java? ]
Up to here the error is gone but the solution is not correct yet since NameSplit[1] and NameSplit[2] are null, because user_input.next(); reads only the first word (*basically until a whitespace (or '\n' if only one word) is detected). So:
2- Change user_input.next(); to user_input.nextLine(); because the nextLine() reads the entire line (*basically until a '\n' is detected)
Read more here: [ http://www.cs.utexas.edu/users/ndale/Scanner.html ]
What would be the best way to split this string directly after the CN= to store both the first and last name in separate fields as shown below?
String distinguisedName = "CN=Paul M. Sebula,OU=BBB,OU=Users,OU=TIES Project,DC=SPHQTest,DC=na,DC=BBBBBB,DC=com"
String firstName"Paul"
String lastName="Sebula"
Don't re-invent the wheel. Assuming these are well-formed DN's, see the accepted answer on this question for how to parse without directly writing your own regex: Parsing the CN out of a certificate DN
Once you've extracted the CN, then you can apply some of the other parsing techniques suggested (use the Java StringTokenizer or the String.split() method as others here have suggested if it's known to be separated only by spaces). That assumes that you can make assumptions (eg. the first element in the resulting array is the firstName,the last element is the lastName and everything in between is middle names / initials) about the CN format.
You can use split:
String distinguisedName = "CN=Paul Sebula,OU=BAE,OU=Users,OU=TIES Project,DC=SPHQTest,DC=na,DC=baesystems,DC=com";
String[] names = distinguisedName.split(",")[0].split("=")[1].split(" ");
String firstName = names[0];
String lastName= names.length > 2 ? names[names.length-1] : names[1];
System.out.println(firstName + " " + lastName);
See IDEONE demo, output: Paul Sebula.
This also accounts for just 2 names (first and last only). Note how last name is accessed it being the last item in the array.
public static void main(String[] args) {
String distinguisedName = "CN=Paul M. Sebula,OU=BBB,OU=Users,OU=TIES Project,DC=SPHQTest,DC=na,DC=BBBBBB,DC=com";
String splitResult[]=distinguisedName.split(",")[0].split("=");
String resultTwo[]=splitResult[1].split("\\.");
String firstName=resultTwo[0].split(" ")[0].trim();
String lastName=resultTwo[1].trim();
System.out.println(firstName);
System.out.println(lastName);
}
output
Paul
Sebula
String distinguisedName = "CN=Paul M. Sebula,OU=BBB,OU=Users,OU=TIES Project,DC=SPHQTest,DC=na,DC=BBBBBB,DC=com"
String[] commaSplit = distinguisedName.split(',');
String[] whitespaceSplit = commaSplit[0].split(' ');
String firstName = whitespaceSplit[0].substring(3);
String lastName = whiteSpaceSplit[2];
In steps:
String distinguisedName = "CN=Paul M. Sebula,OU=BBB,OU=Users,OU=TIES Project,DC=SPHQTest,DC=na,DC=BBBBBB,DC=com";
String fullName = distinguisedName.substring(3, distinguisedName.indexOf(','));
String[] nameParts = fullName.split(" ");
String firstName = nameParts[0];
String lastName = nameParts[nameParts.length-1];
This will work for cases where the middle name/initial are not present as well.