gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 13:18:40 31 4
gpt4 key购买 nike

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

     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/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com