1

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


}

}

L.Jones28
  • 31
  • 4

4 Answers4

1

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());
 }
Rahul Singh
  • 16,265
  • 5
  • 49
  • 74
0

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

user2004685
  • 8,721
  • 4
  • 29
  • 49
  • It's String[2] as the first value is 0, second 1, third 2 :) But thank you for the help anyway! – L.Jones28 Oct 18 '16 at 18:35
  • @L.Jones28 Just keep in mind that indices starts from `0` and while you are reserving the spaces the notion of indices doesn't hold anymore. So it should be `3` instead of just `2`. – user2004685 Oct 18 '16 at 18:39
0

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.

Abhijeet
  • 11
  • 2
0

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 ]

Community
  • 1
  • 1
roxhens
  • 318
  • 2
  • 16