简体   繁体   中英

Why am I getting an ArrayIndexOutOfBoundsException when I try to tokenize the input from the console (Java)?

I'm trying to separate the input from the console using the split method, and then putting each of these values into separate containers, and I keep on getting this error: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1 . I assume the issue is that it ignores the input after the first space, but I am clueless as to why and how to solve that.

Could someone tell me what I'm doing wrong and advise what I should do so that the text after the space is stored in my container? Thank you in advance.

    Scanner s = new Scanner(System.in);

    System.out.println("Input the name and phone no: ");
    String text = s.next();

    String[] temp = text.split(" ");

    String name = temp[0];
    String phoneNoTemp = temp[1];

    System.out.println(name + ": name");
    System.out.println(phoneNoTemp + ": phoneNoTemp");

The input I tried it with was:

Input the name and phone no: 
kate 99912222

Sidenote: Yes, I did import the scanner

Try to use s.nextLine() instead of s.next() because the next() method only consumes until the next delimiter, which defaults to any whitespace.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM