0

I've been looking for an answer to this for a while, but for some reason, none of them seem to work.

public static void main(String[] args) {

    Scanner scanner = new Scanner(System.in);

    System.out.println("Please enter full name (last, first)");
    String[] personalInfo = scanner.next().split(", ");
    String firstName = personalInfo[1];
    String lastName = personalInfo[0];

    System.out.println("Your info: " +  firstName + " " + lastName);

There is my code. I'm basically trying to obtain the personal info, which would be the first and last name. I want to split the first and last name into 2 different strings, but whenever I try to print this, I get the error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 > out of bounds for length 1 at Fines.main(Fines.java:11)

I'm confused because I even started the array with 0 like I was supposed to.. I just don't understand what is going incorrectly.

Please give me a hand - thanks in advance!

  • Read the javadoc of Scanner. What does .next() do? What is a "token"? Is there any other method which would fit better? – JB Nizet Nov 17 '18 at 07:42

3 Answers3

1

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 > out of bounds for length 1 at Fines.main(Fines.java:11)

As the size of the personalInfo is 1 not 2.

use nextLine() instead of next() because next() will only return the input that comes before a space.

String[] personalInfo = scanner.next().split(", "); should be

String[] personalInfo = scanner.nextLine().split(", ");

You might want to read this What's the difference between next() and nextLine() methods from Scanner class?

suvojit_007
  • 1,649
  • 2
  • 12
  • 21
1

What you want is scanner.nextLine() to read from standard input up until end of line. Then split would work as you expected.

Scanner scanner = new Scanner(System.in);

System.out.println("Please enter full name (last, first)");
String[] personalInfo = scanner.nextLine().split(", ");
String firstName = personalInfo[1];
String lastName = personalInfo[0];

System.out.println("Your info: " +  firstName + " " + lastName);
0
try (Scanner scan = new Scanner(System.in)) {
    System.out.println("Please enter full name (last, first)");
    String firstName = scan.next();
    String lastName = scan.next();
    System.out.println("Your info: " + firstName + ' ' + lastName);
}

scanner.next() read until next delimiter (space by default), so it ready only the firstName. Just replace it with scanner.nextLine() or use scanner.next() two times.

oleg.cherednik
  • 12,764
  • 2
  • 17
  • 25