Java - 打印分割字符串的几个不同部分

标签 java while-loop arrays

当我尝试打印数组时遇到错误。虽然我得到了:

     Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
              at FlipProj.main(FlipProj.java:20)

错误消息。

我的代码:

import java.util.Scanner;


public class FlipProj 
{
    public static void main(String args[])
    {
        Scanner s = new Scanner(System.in);

        System.out.println("Innput an equation:");
        String e = s.next();

        String split[] = e.split("-");

        int count = 0;

        while (split.length > count)
        {
                count++;
                System.out.println("Splt: " + split[count]);
        }

        s.close();
    }
}

有什么办法可以正确地做到这一点吗?

最佳答案

你增加得太快了,这应该有效:

while (split.length > count) {
    System.out.println("Splt: " + split[count]);
    count++;
 }

记住数组的索引是从 0 开始的。

需要考虑的一些(更清洁的)替代方案:

//using a for loop
for (int i=0; i<split.length; i++) {
    System.out.println("Splt: " + split[i]);
}

//using an enhanced for loop (since Java 5)
for (String str: split) {
    System.out.println("Splt: " + str);
}

您可以找到更多信息here .

关于Java - 打印分割字符串的几个不同部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22236054/

相关文章:

java - 有条件等待

java - byte [] 和文件 - 当我们有太大的文件时最快的方法

php - mysql while循环的最后一个值

python - 如何在 pygtk 中运行无限 while 循环?

java - 使用 JSON 从字符串中解析数组?

java - println 输出中添加

java - 绑定(bind)对象在 FXML UI Controller 初始化()方法之外不起作用

javascript - 为什么这个 while 循环会记录一个数字?

java - 按升序对数组进行排序

python - 将基本数组写入txt文件?