簡體   English   中英

當我嘗試對來自控制台 (Java) 的輸入進行標記時,為什么會收到 ArrayIndexOutOfBoundsException?

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

我正在嘗試使用 split 方法將輸入與控制台分開,然后將這些值中的每一個放入單獨的容器中,並且我不斷收到此錯誤: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1 我認為問題在於它忽略了第一個空格之后的輸入,但我不知道為什么以及如何解決這個問題。

有人可以告訴我我做錯了什么並建議我應該怎么做才能將空間之后的文本存儲在我的容器中嗎? 先感謝您。

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

我嘗試過的輸入是:

Input the name and phone no: 
kate 99912222

旁注:是的,我確實導入了掃描儀

嘗試使用s.nextLine()而不是s.next()因為next()方法只消耗直到下一個分隔符,默認為任何空格。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM