当我尝试打印数组时遇到错误。虽然我得到了:
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/