猿问

制作一个循环,在遇到冒号字符之前返回字符

每当我运行我的代码时,它都会返回此错误消息:


Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 5

    at java.lang.String.charAt(Unknown Source)

    at codes.Main.main(Main.java:10)

这是我的代码:


    package codes;


public class Main {

    public static void main(String[] args) {

        String cord1 = "Name: x=23 y=60 z= 600";

        String cord2 = "Name: x=200 y=20 z= 300";

        int c1 = cord1.length();

        String mychar = String.valueOf("cord1".charAt(0));

        for (int a = 0; a < c1; a++){

            mychar = String.valueOf("cord1".charAt(a));

            if (mychar == ":"){

                break;

            }else{

                cord1.substring(a);

            }

        }

    }

}


翻翻过去那场雪
浏览 178回答 3
3回答

收到一只叮咚

您的代码中有很多错误..mychar == ":"应该是mychar.equals(":")。由于字符串是不可变的,我们需要使用.equals来比较它们而不是==(<- 这将检查引用是否相等而不是字符串值)。"cord1".charAt应该是你的变量cord1.charAt.. 通过使用"cord1"你基本上创建了一个新的 String 值cord1。cord1.substring(a);不改变cord1值,但返回一个新的字符串。所以你必须保存这个字符串结果,或者打印它,然后用break.使用cord1 = cord1.substring(a)会缩短字符串本身。由于您仍然在原始字符串[0, c1)所在的范围内循环c1,我们仍然会得到一个 StringIndexOutOfBoundsException。相反,你不需要别的情况,并同时需要cord1 = cord1.substring(a)和break如果-包内。(另外,我假设您也想删除它:本身,因此您必须.substring(a+1)改用。)另外,为什么要使用String.valueOf( char )而不是只使用char它们自己?不是真正的要求,但String.valueOf这里有点多余,并且使代码的可读性降低。把它们放在一起:public class Main {&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; String cord1 = "Name: x=23 y=60 z= 600";&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("cord1 before:\t" + cord1);&nbsp; &nbsp; &nbsp; &nbsp; int c1 = cord1.length();&nbsp; &nbsp; &nbsp; &nbsp; char mychar = cord1.charAt(0);&nbsp; &nbsp; &nbsp; &nbsp; for (int a = 0; a < c1; a++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; mychar = cord1.charAt(a);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (mychar == ':'){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; cord1 = cord1.substring(a+1);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("cord1 after:\t" + cord1);&nbsp; &nbsp; }}这将导致最终cord1具有值" x=23 y=60 z= 600"(注意前导空格)。这是一个更简单的替代方案,结果相同:String cord1 = "Name: x=23 y=60 z= 600";String cord1ExcludingName = cord1.replaceFirst("^.*:","");^&nbsp; &nbsp; &nbsp; &nbsp;: Only look at the start of the String for:&nbsp;.*&nbsp; &nbsp; &nbsp;: Zero or more of any character,&nbsp; &nbsp;:&nbsp; &nbsp; : followed by a `:`它将被替换为""(空字符串),因此它们基本上被删除了。

慕少森

String.valueOf("cord1".charAt(0))&nbsp;意味着您正在查看最高索引为 4 的字符串“cord1”的第 0 个字符,这就是为什么它在 5 处给出越界异常。你必须做的是String.valueof(cord1.charAt(0))。这将考虑变量中的字符串cord1。

开心每一天1111

使用等于而不是“==”像这样&nbsp;if (mychar.equals(":")){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;您需要使用 equals 方法,因为您正在使用字符串。每当您使用字符串时,您必须将它们与方法 equals 进行比较。如果你使用char myChar = .....你的代码会起作用。你可以用“==”比较字符
随时随地看视频慕课网APP

相关分类

Java
我要回答