【问题标题】:Why does System.Out.println[array[1]); while using String.split make array out of bounds?为什么 System.Out.println[array[1]);使用 String.split 时使数组越界?
【发布时间】:2018-12-14 14:49:31
【问题描述】:

这是我正在从事的项目的一些基本代码的片段:

System.out.println("ENter a paragraph:")
String input = sc.next();
String[] ArrayIn = new String[100];
ArrayIn = input.split("\\.");

然后我使用 ArrayIn[i] 执行基本的 for 循环。

for (int i = 0; i < ArrayIn.length; i++) {
    System.out.println(ArrayIn[i]);
}

但是任何超过句子的东西,例如我喜欢肉。我喜欢牛肉会打印出我喜欢肉然后会给我一个错误。我只是一个初学者,所以我不知道java的所有内容。你能给我一个简单的解释吗?谢谢。

【问题讨论】:

  • 请发布“基本 for 循环”
  • edit您的问题,不要为此使用cmets。
  • 无论如何,除非你真的想要这个:String[] ArrayIn = new String[100]; 这是自找麻烦。只需String[] ArrayIn = input.split("\\.");
  • @NicholasBegg 实际上这就是 我们you 的要求 :)
  • 来自错误的堆栈跟踪应该准确指出正在生成异常的行号 - 我们需要该行的代码(最好是minimal reproducible example

标签: java arrays input text


【解决方案1】:

改变你的for loop,使用这个

// split phrases by '.'
String[] sentences= input.split("\\.");
for(int i = 0; i < sentences.length; i++) {
    System.out.println(sentences[i]);
}

您的问题是您使用的是sc.next()。这意味着当您的输入是hello world. bye 时,它将把它当作由空格分隔的3 个不同的输入['hello', 'world.', 'bye']。您应该改用sc.nextLine()。那么完整的代码就是

Scanner sc = new Scanner(System.in);
System.out.println("ENter a paragraph:");
String input = sc.nextLine();
String[] sentences = input.split("\\.");
for (int i = 0; i < sentences.length; i++) {
    System.out.println(sentences[i]);
}

【讨论】:

  • 我会尝试这样做。现在,我的电脑工作不正常。
  • @NicholasBegg 你能分享错误吗?你的代码对我很好,没有错误。
  • 第 26 行 java.lang.arrayindexoutofboundsexception
  • 所以它基本上打印食物味道好,然后是java.lang.arrayindexoutofboundsexception
  • 能否请您与我分享您的代码,以便我进行比较?
【解决方案2】:

您的代码中唯一的问题是这一行:

String input = sc.next();

应该改为:

String input = sc.nextLine();

因为您想拆分整行。
这些行:

String[] ArrayIn = new String[100];
ArrayIn = input.split("\\.");

不会产生任何错误,但可以合并到:

String[] ArrayIn = input.split("\\.");

所以我看不出您发布的代码中有任何错误的原因。
也许这不是全部代码。

【讨论】:

  • 谢谢,是不是因为它只使用next()读取下一个单词?
  • 是的,这就是 next() 的作用。
  • 谢谢。我早该知道的!直到现在我才发现有什么不同。
【解决方案3】:

next() 只能读取输入直到空格。它无法读取以空格分隔的两个单词。此外,next() 在读取输入后会将光标置于同一行。

nextLine() 读取输入,包括单词之间的空格(也就是说,它读取到行尾 \n)。读取输入后,nextLine() 将光标定位到下一行。

这就是为什么使用: sc.nextLine()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-07
    • 1970-01-01
    • 2014-11-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多