Trying to split up a string with blank space - java

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 ]

Related

how to input username by getting the half of the first name and half of the last name and the day of the given birthday

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 index out of range on space bar character

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);

Splitting a user inputted string and then printing the string

I am working through a piece of self study, Essentially I am to ask the User for a string input such as "John, Doe" IF the string doesnt have a comma, I am to display an error, and prompt the user until the string does indeed have a comma (Fixed.). Once this is achieved I need to parse the string from the comma, and any combination of comma that can occur (i.e. John, doe or John , doe or John ,doe) then using the Scanner class I need to grab John doe, and split them up to be separately printed later.
So far I know how to use the scanner class to grab certain amounts of string up to a whitespace, however what I want is to grab the "," but I haven't found a way to do this yet, I figured using the .next(pattern) of the scanner class would be what I need, as the way it was written should do exactly that. however im getting an exception InputMismatchException doing so.
Here is the code im working with:
while (!userInput.contains(",")) {
System.out.print("Enter a string seperated by a comma: ");
userInput = scnr.nextLine();
if (!userInput.contains(",")) {
System.out.println("Error, no comma present");
}
else {
String string1;
String string2;
Scanner inSS = new Scanner(userInput);
String commaHold;
commaHold = inSS. //FIXME this is where the problem is
string1 = inSS.next();
string2 = inSS.next();
System.out.println(string1 + " " + string2);
}
}
This can be achieved simply by splitting and checking that the result is an array of two Strings
String input = scnr.nextLine();
String [] names = input.split (",");
while (names.length != 2) {
System.out.println ("Enter with one comma");
input = scnr.nextLine();
names = input.split (",");
}
// now you can use names[0] and names[1]
edit
As you can see the code for inputting the data is duplicated and so could be refactored

Trying to store values from a a text file but it outputting incorrectly [duplicate]

This question already has answers here:
How do I use a delimiter with Scanner.useDelimiter in Java?
(3 answers)
Closed 5 years ago.
Here is my program currently for retrieving data from the text file which looks like this:
try {
File file = new File("dataCollection.txt");
Scanner s = new Scanner(file);
while(s.hasNext()){
String firstName = s.next();
String lastName = s.next();
String address = s.next();
String suiteNumber = s.next();
String city = s.next();
String state = s.next();
String zipCode = s.next();
String balance = s.next();
System.out.println("First Name is " + firstName);
}
s.close();
The input file looks like this:
FirstNameFXO|LastFXO|2510 Main Street|Suite 101D|City100|GA|72249|$280.80
FirstNamePNR|LastPNR|396 Main Street|Suite 100A|City102|GA|24501|$346.01
FirstNameXZU|LastXZU|2585 Main Street|Suite 107C|City101|GA|21285|$859.40
I am trying to print out just the firstName so I can use the values later for various other uses but it outputs this instead (the output is much larger, this is just the first three lines):
First Name is FirstNameFXO|LastFXO|2510
First Name is FirstNameXZU|LastXZU|2585
First Name is FirstNameGHP|LastGHP|2097
the problem that you are using method .next() which has default delimiter whitespace so it will read and return the next series of string token until a whitespace is reached.
in your case it will return:
firstname ="FirstNameFXO|LastFXO|2510";
to solve your problem instead you can use method .nextLine()
read each line then save it in variable line and substring it to get the First Name:
while(s.hasNextLine()){
String line = s.nextLine();
String firstname = line.substring(0,line.indexOf("|"));
System.out.println("First Name is " + firstName);
}

Splitting String after whitespace and then referencing it

The purpose of the program is to take the user input of his full name then break it down into his first name and last name(besides doing a few additional things).
It is supposed to split the String in half in between the whitespace, but I can only reference the first value of the split array, otherwise I get:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at FirstNameLastName.main(FirstNameLastName.java:41)
Here is the current code, any help would be appreciated:
import java.util.Scanner;
public class FirstNameLastName {
public static void main(String[] args) {
String fullName; //the users full name as he enters it
String fname; //the users first name
int fnameCount; //number of characters in fname
String lname; //the users last name;
int lnameCount; // counts amount of characters in lname
String init; //initials of the user, combination of first and last name
Scanner input = new Scanner(System.in);
System.out.println("Please input your first and last name with a space inbetween them");
fullName = input.next();
String[] parts = fullName.split("\\s+"); // creates an array within which the two split String values are stored
fname = parts [0];
lname = parts [1];
fnameCount = fname.length();
lnameCount = lname.length();
System.out.println(fname);
System.out.println(lname);
System.out.printf("Your first name is %s , which has %d characters" , fname , fnameChar);
System.out.println();
System.out.printf("Your last name is %s , which has %d characters" , lname , lnameChar);
System.out.println();
System.out.printf("Your initials are %c%c", fname.charAt(0),lname.charAt(0));
}
}
Your problem is
fullName = input.next();
which reads only a single word. You want it to be
fullName = input.nextLine();
which will read an entire line.

Categories

Resources