0

Whenever I run my code it returns this error message:

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)

Here is my code:

    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);
            }
        }
    }
}
AncientSwordRage
  • 7,086
  • 19
  • 90
  • 173
  • You need: `mychar = cord1.charAt(a);` – LuCio Sep 06 '18 at 10:16
  • `cord1.substring(a);` is useless, because strings in Java are imutable and `cord1.substring(a);` Returns a new string – Jens Sep 06 '18 at 10:17
  • 2
    And this `if (mychar == ":"){` is useless. Don't compare Strings using `==` or `!=`. Use the `equals(...)` or the `equalsIgnoreCase(...)` method instead. Understand that `==` checks if the two *object references* are the same which is not what you're interested in. The methods on the other hand check if the two Strings have the same characters in the same order, and that's what matters here. – Hovercraft Full Of Eels Sep 06 '18 at 10:17
  • `"cord1".charAt(0))` returns the first letter or the word `curd1` not of the Content of the variable – Jens Sep 06 '18 at 10:17
  • You have multiple problems, but honestly, go easy on yourself and just use `str.replaceAll(":.*$", "")`. One-liner, and much harder to go wrong. – Tim Biegeleisen Sep 06 '18 at 10:18
  • Also why do you not use String to stor a character not a `char` – Jens Sep 06 '18 at 10:19
  • You never printout the result – Jens Sep 06 '18 at 10:20
  • Possible duplicate of [Keep Getting StringIndexOutOfBoundsException](https://stackoverflow.com/questions/9141858/keep-getting-stringindexoutofboundsexception) – Naveen Kumar M Sep 06 '18 at 10:33
  • @TimBiegeleisen Umm.. shouldn't that be `str.replaceAll("^.*:","")` instead.. Removing your `:.*$` would output "Name", and based on his `.substring(a)` I assume he wants to remove the `Name:` part and have the coordinates.. Not sure, though.. >.> – Kevin Cruijssen Sep 06 '18 at 10:35
  • @KevinCruijssen After re-reading the code, I think you might be right :-) – Tim Biegeleisen Sep 06 '18 at 10:43

3 Answers3

1

There are multiple things wrong in your code..

  1. mychar == ":" should be mychar.equals(":") instead. Since Strings are immutable, we need to use the .equals to compare them instead of == (<- this checks if the references are equal instead of the String-values).
  2. "cord1".charAt should be your variable cord1.charAt.. By using "cord1" you basically create a new String with the value cord1.
  3. cord1.substring(a); doesn't change the cord1 value, but returns a new String. So you'll have to save this String result, or print it, and then stop the loop with a break.
  4. Using cord1 = cord1.substring(a) would shorten the String itself. Since you still loop in the range [0, c1) where c1 was the original String, we would still get a StringIndexOutOfBoundsException. Instead, you don't need the else-case and need both the cord1 = cord1.substring(a) and break inside the if-case. (Also, I assume you want to remove the : itself as well, so you'll have to use .substring(a+1) instead.)
  5. Also, why use String.valueOf( char ) instead of just using the char themselves? Not really a requirement, but the String.valueOf is kinda redundant here, and makes the code less readable.

Putting it all together:

public class Main {
    public static void main(String[] args) {
        String cord1 = "Name: x=23 y=60 z= 600";
        System.out.println("cord1 before:\t" + cord1);
        int c1 = cord1.length();
        char mychar = cord1.charAt(0);
        for (int a = 0; a < c1; a++){
            mychar = cord1.charAt(a);
            if (mychar == ':'){
                cord1 = cord1.substring(a+1);
                break;
            }
        }
        System.out.println("cord1 after:\t" + cord1);
    }
}

Which will result in cord1 having the value " x=23 y=60 z= 600" (note the leading space) in the end.

Try it online.


Here is a much simpler alternative with the same result:

String cord1 = "Name: x=23 y=60 z= 600";
String cord1ExcludingName = cord1.replaceFirst("^.*:","");

Try it online.

^       : Only look at the start of the String for:
 .*     : Zero or more of any character,
   :    : followed by a `:`

Which will be replaced with "" (an empty String), so they're basically removed.

Kevin Cruijssen
  • 9,153
  • 9
  • 61
  • 135
0

Use equals instead of "==" Like this

 if (mychar.equals(":")){
            break;

You need to use equals method because you are working with a string. Whenever you work with string u must compare them with the method equals. If you used

char myChar = .....

Your code would work. You can compare chars with "=="

Sasori
  • 1
0

String.valueOf("cord1".charAt(0)) means you are looking into the 0th character of string "cord1" which has a highest index of 4, that is why it is giving out of bound exception at 5.

What you have to do is String.valueof(cord1.charAt(0)). This will consider the string in the variable cord1.

Muhammad Areeb
  • 92
  • 2
  • 14