Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 正在拆分索引为超出范围的字符串_Java_Runtime Error - Fatal编程技术网

Java 正在拆分索引为超出范围的字符串

Java 正在拆分索引为超出范围的字符串,java,runtime-error,Java,Runtime Error,我尝试编写逻辑代码,以打印给定字符串是否是其他字符串的置换, 发生运行时错误 “java.lang.ArrayIndexOutOfBoundsException” 我只访问了字符串数组的两个索引 ->给定的字符串由两个空格分隔 public static String permute(String str){ String[] st=str.split("\\s+"); String sr1=st[0].toString();//Run time error String

我尝试编写逻辑代码,以打印给定字符串是否是其他字符串的置换,
发生运行时错误

“java.lang.ArrayIndexOutOfBoundsException”

我只访问了字符串数组的两个索引

->给定的字符串由两个空格分隔

public static String permute(String str){
    String[] st=str.split("\\s+");
    String sr1=st[0].toString();//Run time error
    String sr2=st[1].toString();
}
运行时错误消息:“java.lang.ArrayIndexOutOfBoundsException”


请避免此错误。

代码的问题在于,您假设数组中有两个项目,但并非所有输入都是这样。 你应该考虑数组大小:

public static String permute(String str){
    String[] st=str.split("\\s+");
    for (String item : st) {
       // do whatever
    }
}

如果您只想处理前两个项,而不管是否有更多项,请执行类似于(int i=0;i,但在访问数组项之前,请始终验证数组的长度。

代码的问题在于,您假设数组中有两个项,但并非所有输入都是如此。 你应该考虑数组大小:

public static String permute(String str){
    String[] st=str.split("\\s+");
    for (String item : st) {
       // do whatever
    }
}

如果您只想处理前两项,而不管是否有更多项,请执行类似于(int i=0;i操作,但始终在访问数组项之前验证数组的长度

向我们显示您尝试拆分的
字符串
。感谢用于
split()
的模式不是字面上的
两个空格,而是一个或多个空格-如果没有空格,如果第二个字符串是所有空格怎么办?向我们展示您尝试拆分的
字符串。感谢用于
split()
的模式不是字面上说的
两个空格,而是一个或多个空格-如果没有空格,如果第二个字符串是所有空格怎么办?。