split返回一个字符串来代替字符串数组

时间:2017-05-10 16:50:16

标签: java string split indexoutofboundsexception

每当我尝试读取java中的字符串并将其拆分为使用String[] part=str.split(" ")获取字符串数组时,它将返回一个数组而不是返回一个字符串数组,即part。 length=1因此在访问时会发出ArrayIndexOutOfBoundException

这是我目前正在处理的代码:

import java.io.*;
import java.util.*;
public static void main(String[] args)
{
    InputReader in = new InputReader(System.in);
    String s=in.readString();
    String[] str=s.split(" ");
    for(int i=0;i<str.length;i++)
        System.out.println(str[i]);
}
private static class InputReader
{
    private InputStream stream;
    private byte[] buf = new byte[1024];
    private int curChar;
    private int numChars;
    private SpaceCharFilter filter;

    public InputReader(InputStream stream)
    {
        this.stream = stream;
    }

    public int read()
    {
        if (numChars == -1)
            throw new InputMismatchException();
        if (curChar >= numChars)
        {
            curChar = 0;
            try
            {
                numChars = stream.read(buf);
            } catch (IOException e)
            {
                throw new InputMismatchException();
            }
            if (numChars <= 0)
                return -1;
        }
        return buf[curChar++];
    }

    public int readInt()
    {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        int sgn = 1;
        if (c == '-')
        {
            sgn = -1;
            c = read();
        }
        int res = 0;
        do
        {
            if (c < '0' || c > '9')
                throw new InputMismatchException();
            res *= 10;
            res += c - '0';
            c = read();
        } while (!isSpaceChar(c));
        return res * sgn;
    }

    public String readString()
    {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        StringBuilder res = new StringBuilder();
        do
        {
            res.appendCodePoint(c);
            c = read();
        } while (!isSpaceChar(c));
        return res.toString();
    }
    public double readDouble() {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        int sgn = 1;
        if (c == '-') {
            sgn = -1;
            c = read();
        }
        double res = 0;
        while (!isSpaceChar(c) && c != '.') {
            if (c == 'e' || c == 'E')
                return res * Math.pow(10, readInt());
            if (c < '0' || c > '9')
                throw new InputMismatchException();
            res *= 10;
            res += c - '0';
            c = read();
        }
        if (c == '.') {
            c = read();
            double m = 1;
            while (!isSpaceChar(c)) {
                if (c == 'e' || c == 'E')
                    return res * Math.pow(10, readInt());
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                m /= 10;
                res += (c - '0') * m;
                c = read();
            }
        }
        return res * sgn;
    }
    public long readLong() {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        int sgn = 1;
        if (c == '-') {
            sgn = -1;
            c = read();
        }
        long res = 0;
        do {
            if (c < '0' || c > '9')
                throw new InputMismatchException();
            res *= 10;
            res += c - '0';
            c = read();
        } while (!isSpaceChar(c));
        return res * sgn;
    }
    public boolean isSpaceChar(int c)
    {
        if (filter != null)
            return filter.isSpaceChar(c);
        return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
    }

    public String next()
    {
        return readString();
    }

    public interface SpaceCharFilter
    {
        public boolean isSpaceChar(int ch);
    }
}

}

例如,每当我写“你好我在这里”时,它必须在4个单独的行中打印“hello”,“I”,“am”和“here”,而在我的情况下,它只打印“hello”。 / p>

如何解决此问题?

enter image description here

3 个答案:

答案 0 :(得分:0)

您的代码看起来很好,并且没有问题。我们可以用字符串“s”来猜测这个问题,因为“split”效果很好。 当你的字符串“s”中没有符号“”时,你将在“str”中有一个元素,不要数组。

例如,您可以选择代码来发现问题:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.JFileChooser;

public class ReadFileTxt {

    static File fileName;
    static ArrayList<String[]> data = new ArrayList<String[]>();

    public ReadFileTxt() {
        readFile();
    }

    public static void readFile() {
        String str;
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setVisible(true);
        int result = fileChooser.showOpenDialog(fileChooser);
        if (result == JFileChooser.APPROVE_OPTION) {
            fileName = fileChooser.getSelectedFile();
        }
        try {
            FileReader fr = new FileReader(fileName);
            BufferedReader reader = new BufferedReader(fr);
            str = reader.readLine();
            while (str != null) {

                // Delete redundant blanks
                for (int i = 0; i < str.length(); i++) {
                    str = str.replace("  ", " ");
                }
                String[] strMas = str.split(" ");
                data.add(strMas);
                str = reader.readLine();
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new ReadFileTxt();
    }
}

它的txt文件:

1                      XXXXXXXX                  12342
2                      YYYYYYY                    45321
3                      ZZZZZZZZZ               5454532

答案 1 :(得分:0)

我没有看到您的程序代码有任何问题我测试它并且它返回了您想要的结果

我认为在读取字符串s时此行存在问题:

String s = in.readLine();

您可以测试此code并查看输出:

    Scanner in = new Scanner(System.in);
    String s = in.nextLine();
    String[] str = s.split(" ");
    for(int i = 0; i < str.length; i++){ 
        System.out.println(str[i]);
    }

<强>更新

我测试你的InputReader类方法并发现这个方法的问题readString()它只读取行中的单个字符串并忽略空格字符后面的所有字符串:

    InputReader in = new InputReader(System.in);
    String s = in.readString();
    System.out.println(s); 

如果您在字符串"hello I am here"上测试此代码,它将仅返回hello,因此您应该使用readString方法解决问题以获得正确的输出。

检查此readString()新实施,以解决您完美运行的问题:

public String readString()
{
        int c = read();
        while (isSpaceChar(c))
            c = read();
        StringBuilder res = new StringBuilder();
        do
        {
            res.appendCodePoint(c);
            c = read();
        } while (c != '\n'); // stop reading at the end of line
        return res.toString();
}

答案 2 :(得分:-1)

item_number 340-1018-000 340-9922-000 9400-2007 方法只是读取一个空格,也就是下一个单词 - 这里是代码中的相应部分(这不是一个解决方案,只是从无法正常工作的代码中复制和粘贴) ):

readString

无需调用拆分,因为public String readString() { ... // ignore spaces at start do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); // STOPS reading if it got a space return res.toString(); } 已经在完成工作。

但真的需要InputReader吗?看看InputReader课程。