【发布时间】:2017-10-09 10:57:31
【问题描述】:
每当我尝试在 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 个单独的行中打印“你好”、“我”、“我”和“这里”,理想情况下,它只打印“你好”。
如何解决这个问题?
【问题讨论】:
-
你的代码请
-
ypu要拆分什么字符串?
-
请说明它是返回一个字符串,还是一个大小为 1 的字符串数组,其中原始字符串作为数组的唯一元素。
-
但是 s 里面的值是什么?
-
我个人不能,工作阻止了 imgur 网站。通常最好将实际信息实际放入,而不是将其放入图片中。
标签: java string split indexoutofboundsexception